home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1998 May: Tool Chest / Dev.CD May 98 TC.toast / Tool Chest / Sound / SoundApp / SoundApp.c < prev    next >
Encoding:
Text File  |  1997-02-18  |  170.4 KB  |  4,681 lines  |  [TEXT/CWIE]

  1. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2. /*
  3. Apple Macintosh Developer Technical Support
  4.  
  5. MultiFinder-Aware SoundApp Application
  6.  
  7. SoundApp
  8.  
  9. SoundApp.c - C Source
  10.  
  11. Jim Reekes - Macintosh Developer Technical Support
  12. Copyright © 1989-1994 Apple Computer, Inc.
  13. All rights reserved.
  14.  
  15. Versions:
  16.         1.03                January, 1990
  17.         1.04                Sept, 1990
  18.         1.2                    August, 1994        translated to C
  19.  
  20. Components:
  21.         SoundApp.c            January, 1990        MPW C source code
  22.         SoundUnit.c            January, 1990        MPW C source code
  23.         SoundUnit.h            January, 1990        MPW C source code
  24.         SoundApp.r            January, 1990        MPW Rez source code
  25.         SoundAppSnds.r        January, 1990        MPW Rez source code
  26.         SoundApp.make        January, 1990        MPW build script
  27.  
  28. Formatting was done with FONT = Courier or Monaco, SIZE = 10, TABS = 4
  29.  
  30. Version comments
  31.  
  32. 1.04: This was an update to support the Utilities Unit that MacDTS
  33. developed.  Some of it was routines formally created for SoundApp,
  34. with additional ones coming from other sources.  This helps to reduce
  35. the "destractive" code from the samples and makes them easier to maintain.
  36.  
  37. 1.1:     • This is the "new" SoundApp which adds some new features.
  38.         • Some knowledge of the new Sound Manager is present
  39.           in areas that were work-arounds for old Sound Manager bugs
  40.         • Recording of sounds is now possible with the Sound Input Manager
  41.         • The document window will keep the Record button hidden if
  42.           the Sound Inpute Manager is not available for recording,
  43.           otherwise it will expand the window size to show this button.
  44.         • Supports copy and pasting of sound resources
  45.         • Conversion to MPW 3.2 was established (with some amount of pain)
  46.         • SoundApp now has its own documents
  47.         • Supports launching by open documents from Finder
  48.         • Added color icons for the System 7.0 desktop
  49.         • Added the new Sound Manager error strings
  50.         • DoErrorSound tests for safe beeps
  51.         • Made Apple Legal happy by getting rid of the xxxxCmd
  52.           and changed it to the freqDurationCmd.  Also got rid of
  53.           any other use of the work "xxxx" in a musical context
  54.  
  55. 1.2:    • Translated into C, some clean up along the way
  56.         • Using universal headers
  57.         • Gave up on the DTS utilities code, everything is self-contained
  58.  
  59. Formatting was done with FONT = Courier, SIZE = 10, TABS = 4
  60.  
  61. many thanks to: Bo3b Johnson, Mark Bennett, Andy Shebanow, Keith
  62. Rollin, Chris Derossi, Pete Helme, Darin Adler, and my co-workers that
  63. sat near me while I was making lots of noise testing this application.
  64.  
  65. To the reader,
  66.  
  67. SoundApp.p is a sample application source file for demonstrating
  68. the Sound Manager.  It requires the use of the SoundUnit to handle
  69. all of the sound routines.  This portion of the source code handles the
  70. application’s management of memory, errors, user interface, etc..
  71. The read me notes are here in the source code because people tend to
  72. not read them otherwise.
  73.  
  74. SoundApp is a demonstration of the Sound Manager released in System
  75. 6.0.x.  SoundApp is also a example of how to write a Macintosh
  76. application that performs good user interface and proper error
  77. handling.  Believe it or not, but the Sound Manager portion was the
  78. easiest part for me to write.  It was all the user interface and error
  79. handling that was the most difficult.  One thing became very clear to
  80. me in the course of writing this application.  The following axiom is
  81. one of the few great truths in the universe.
  82.  
  83. If you write a Macintosh application without MacApp, you’re working
  84. too hard.
  85.  
  86. Throughout the development of SoundApp I would run into typical
  87. situations that make programming a Macintosh too hard.  When this
  88. happened I asked myself “what would MacApp do?” and that was followed
  89. by the thought “then why am I writing code that is already out there
  90. for me to use?”  I started out intending on writing a very simple
  91. application that anyone could read, and understand the Sound Manager.
  92. I felt this meant not requiring the person to read Object Oriented
  93. Pascal.  I accomplished part of my goal.  People should be able to
  94. learn how to use the Sound Manager (in its present condition), but it
  95. didn’t turn out to be such a simple application as I had hoped for.
  96.  
  97. I have put a large amount of comments into the code.  This is
  98. something I’m really picky about.  People do not comment their code
  99. enough.  Each procedure has a paragraph that should explain what to
  100. expect that routine to do, and how it goes about doing it.  There are
  101. some bigger issues that I will put into the release notes below.
  102. There are some things that make the Macintosh harder to develop for
  103. than it should be.  Simple things should be simple.  Too many things
  104. on the Mac that should be simple are not.  Maybe someday these things
  105. will be fixed.
  106.  
  107. • GetFontInfo requires a port set to the font in question.  If I
  108. wanted to find the height of the System Font, I had to first set the
  109. current port to the WindowMgr.  I could have used my own window, but
  110. what if I needed the font info before I had a window available?
  111. • The toolbox blows chunks when your heap gets “too low.”  I believe
  112. this magical number is between 32k and zero.  The odds of blowing
  113. chunks increase logarithmically as one approaches 0 free bytes.
  114. • The Dialog Manager is not a free lunch and in fact will cost you
  115. plenty.
  116. • There’s no safe way to determine how much memory opening a
  117. resource file will take away from your heap.
  118. • There’s no way to determine how safe it is opening a resource that
  119. could be shared by other applications, especially on a local volume.
  120. • The Resource Manager doesn’t always set ResErr.
  121. • The Sound Manager returns even less errors.
  122. • The List Manager returns no errors.
  123. • Writing a staggering routine for new windows encompasses a number
  124. of difficulties.  How does one find the height of a window’s title
  125. region before the window is visible?
  126.  
  127. Am I just a complainer?  Do I have a bad attitude?  Probably, but
  128. I’m just trying to point out the above areas make the Mac programming
  129. experience difficult.  These are areas that get developers into
  130. trouble.  These areas need a sign in front of them that says,
  131. “Danger!”  These are areas that developers get into and then write to
  132. MacDTS for help.
  133.  
  134. Notation Conventions
  135. --------------------
  136. All global variables begin with a lower case “g”.
  137. All constants begin with “k” except for those noted here.
  138. Resource IDs begin with “r”.
  139. Menu IDs being with “m” and items with an “i”.
  140. Resource strings begin with “s”.
  141.  
  142. Human Interface
  143. ---------------
  144. This is the most important and about the most difficult aspect of
  145. programming on the Macintosh.  In the development of SoundApp I gave much
  146. thought to the human interface issues.  In fact, in talking with the Human
  147. Interface Group additions to the existing guidelines were made.  The
  148. method of window stacking used here was a new one.  This was documented in
  149. a Human Interface Tech Note.  I even made one compromise (hard to
  150. believe!) suggested by the Human Interface Group.  I originally had the
  151. buttons and the list in my choice of font and size.  They felt that
  152. buttons should be in the System font and the list should also be the same.
  153. I liked my font choice better, but the group had a point that I really
  154. couldn’t argue with.  That was, “If there isn’t a compelling reason to
  155. change something standard, then don’t change it.”  Buttons on a Macintosh
  156. typically appear in the System font.  Changing the font, just because I
  157. wanted to, was considered gratuitous.  Standard File is in the System font
  158. and it also contains a list and buttons.  Since my window are very similar
  159. to that dialog, I’m using the System Font.
  160.  
  161. SoundApp is never modal unless an error occurs and I need to show and
  162. alert.  Controls are inactivated for inactive windows.  The default button
  163. is given the proper outline, and this outline disappears when the window
  164. is deactivated.  Keyboard equivalents for the buttons cause the button to
  165. appear as if it had been clicked in.  The check box in the Standard File
  166. dialog remembers the user’s last setting.  The about box is only
  167. semi-modal.  It will allow the user access to switch to another application.
  168. The status window under some circumstances was found to disappear too quickly,
  169. so a built in delay was added.  Windows are centered or stacked according
  170. to the Human Interface Guidelines.  The sound level isn’t adjusted by the
  171. application, and instead the users is informed of the current level and
  172. told how it can be adjusted.
  173.  
  174. The About box
  175. -------------
  176. It’s rad.  Has a color icon, shows the 'vers' resource, goes Moof!™.  It
  177. also demonstrates how to handle a modal window without the Dialog Manager.
  178. This technique can be use for any window, including dialog windows.  The
  179. dialog’s update routine would call UpdtDialog.  The really new point to
  180. notice is this window is modal but ONLY within the application’s layer.
  181. While running under MultiFinder, the user can switch to other
  182. applications.  While the About window is present, it is the only window
  183. belonging to the application that accepts user actions.
  184.  
  185. Memory Management
  186. ----------------
  187. This has to be the most difficult portion of a Mac application to
  188. write.  This along with the user interface.  I spent too many nights
  189. chasing down crashes while running the application under low memory.
  190. I found unpleasant surprises while doing this.  The Sound Manager
  191. doesn’t check for NIL pointers.  OpenResFile may take large portions
  192. of my heap away.  The toolbox seems to need at least 32k of free space
  193. in the heap of my Mac II running color.
  194.  
  195. I wrote a simple grow zone procedure that will dump a reserve memory
  196. block.  This is only considered for use in an emergency.  I never rely
  197. on using it directly.  If the reserve has been released, I will not
  198. continue an operation such as playing a sound or showing the status
  199. window until it is regained.  Grow zones should not be considered a
  200. solution to memory management.  They can be used to augment your
  201. overall memory management scheme.
  202.  
  203. Error Checking
  204. --------------
  205. Lots and lots and lots of it.  I could even do more.  Programmers
  206. need to do more of this.  The Sound Manager will crash when
  207. encountering a NIL pointer.  My application should never crash.  If
  208. you can find a way to crash this application, then I want to hear
  209. about it.  Using a bogus 'snd ' resources doesn’t count and I’ve found
  210. many of those.  Writing proper error checking into the code during
  211. development really helped.  Always handle errors, and pass along the
  212. error.  I will let the first error encountered to be passed all the
  213. way up to the caller and eventually my error dialog will show up for
  214. the user.
  215.  
  216. SetPort Strategy
  217. ----------------
  218. Any routine that needs to use Quickdraw will set the port.  I do not
  219. believe that it should also be responsible for restoring the port back
  220. to what it may have been before the routine was called.  So, you’ll
  221. find there is an absence of the GetPort, SetPort, do my thing, and
  222. then SetPort again.  Instead I SetPort and do my thing.  The Mac often
  223. is setting the port unnecessarily.
  224.  
  225. Strings
  226. -------
  227. All of my strings are resources.  There are no strings that appear
  228. within the code.  This helps memory management and allows me to adjust
  229. the application to international systems without compiling any code.
  230. I could simply use ResEdit, or some other tool, to localize this
  231. application.  I find it is just as easy to run Rez again than
  232. attempting to use ResEdit.  Besides, after editing with ResEdit I want
  233. the source for that and would have to run DeRez which isn’t nearly as
  234. clean as my original source files.
  235.  
  236. Window Stacking
  237. ---------------
  238. I hate applications that will open a new document that covers up an
  239. existing document, unless the new document covers the entire screen.
  240. So, my application’s documents have a small window size.  I wanted to
  241. open new windows that would not cover up older ones.  This is nice for
  242. the user, since they will not have to move windows just to get at
  243. other documents.  ResEdit will stagger new windows off of the
  244. frontmost window but I find that this isn’t the best approach.  It
  245. will still cover up other windows and I also don’t like windows that
  246. will open half way between two monitors.  I wanted a better approach:
  247. one that would always stagger new windows and not cover up older ones.
  248.  
  249. When I want to center a window, I need to know its entire rectangle
  250. size.  The rub is that I cannot determine its size until I show it
  251. because I only know about the window’s boundsRect.  This does not
  252. include the area that contains the title bar.  That’s the strucRgn,
  253. which is an empty region for an invisible window.  I could do what
  254. MacApp does, but if I have to do another thing that MacApp already
  255. does I’ll give up and stick with MacApp.  I ended up writing a routine
  256. that takes a guess at the height of the window’s title bar.  This is
  257. another thing that was harder than it should have been.
  258.  
  259. Dialog Manager (and some of the reasons I don’t like it)
  260. --------------------------------------------------------
  261. My first approach was to use modeless dialogs for document windows,
  262. thinking that I could write an application that would demonstrate how to
  263. deal with them and all of their idiosyncrasies.  Not long into the
  264. development cycle it became obvious to me that I was fighting something
  265. that contained more disadvantages than advantages.  I removed all the
  266. dialog code and only used standard windows and controls the old fashion
  267. way.  In the case of the About window, which is semi-modal, I have a test
  268. that will return TRUE for a window that should be treated as modal.  This
  269. allows my window to be handled by my standard event handlers and I don’t
  270. have to write dialog filters.  There are some things that do not get
  271. handled properly while calling ModalDialog.  ModalDialog ignores disk
  272. insert events.  The activate or update events do not get handled for
  273. background windows.  Using a modeless dialog fails with MultiFinder if
  274. switching takes place while the dialog is the frontmost window.  The
  275. problem is that DialogSelect ignores and removes the suspend/resume event.
  276. Another advantage to all this is that drawing was much faster.
  277.  
  278. As an example of some of the problems with ModalDialog and the activate
  279. event.  Try this with the Finder.  Open a window and choose “View by name.”
  280. Then select a few names with the shift key and resize the window so the
  281. vertical scroll bar is visible.  Move this window to one edge of the
  282. screen or a second monitor.  Now choose “Set Startup.”  This is a modal
  283. dialog.  If you look at the Finder window with the selected files, you’ll
  284. notice that the scrollbar and the text are still highlited.  This is not
  285. the proper user interface.  This is because the deactivate routines are
  286. not called while in ModalDialog.  You can even find this problem with
  287. SoundApp.  On deactivate events I will change my controls to the inactive
  288. state.  If you place the buttons to the side of the screen and then bring
  289. up the standard file dialog, you’ll notice that the buttons don’t change
  290. properly.  ModalDialog also prevents the application from updating
  291. background windows too.  To solve this a dialog filter procedure is
  292. required.  In most cases, this filter would be as complex and the event
  293. loop.  It would also make it necessary to call your event routines from
  294. outside of the normal event loop.  All on this isn’t worth the effort.
  295.  
  296. You can see how this does not happen while using this application’s
  297. About window.  Select an item in the document window and choose “Play
  298. Melody.”  This will leave the status window on screen so that you can
  299. drag it to cover the document window.  Now select “About SoundApp” to
  300. bring up the about window.  This causes the status window to close,
  301. which uncovers the document window leaving an invalid area.  The
  302. document window gets an activate event, then the About window appears.
  303. Then the document window is properly deactivated and updated.  Yeah,
  304. just like it should happen.
  305.  
  306. So, the tradeoff was that I didn’t have to work around all the
  307. strange things the Dialog Manager does such as running a secondary
  308. event loop, and requiring me to have userItems or filterProcs.  This
  309. made the code smaller, more readable, and faster.  I think I will
  310. avoid the Dialog Manger from now one unless I’m using a very simple
  311. dialog.  The about window of this application proved too much for the
  312. Dialog Manager.
  313.  
  314. One thing dialogs are good for is running ResEdit and laying out the
  315. dialog.  To help position controls, I used a DLOG resource of the same
  316. size as my WIND resource.  The DITL of this dialog contains the
  317. positions I wanted for my CNTL resources.  This helped me to look at
  318. where I could expect my buttons to show up.  This is one of the main
  319. reasons people think they need the Dialog Manager, because ResEdit
  320. makes it easy to build dialogs.  ResEdit alone has contributed to
  321. nearly all of the Dialog Manager abuse in the world today.
  322.  
  323. I used a Rect resource for positioning the list rectangle of the
  324. document windows.  These windows look very much like a modeless
  325. dialog.  (They used to be, but that presented to many problems.)  The
  326. About window is also a standard window, but shown modally.  Just like
  327. ModalDialog, but my modal window does allow switching under
  328. MultiFinder.  You can change the window to a dBoxProc and then
  329. MultiFinder will not switch while this is the active window.  To help
  330. with the layout of the about window, I position the text within it
  331. based on the size of the window.  The status window does this too.
  332. These two things, the Rect resource and text based on the size of the
  333. window, help when changing the text.  If the new text doesn’t fit,
  334. then resize the window’s resource.  I used some trick with Rez to help
  335. layout my window contents.  Refer to the SoundApp.r sources.
  336.  
  337. I’ve read and understood Tech Note 203, and have learned how to
  338. apply it.  Bo3b Johnson is a smart guy, and developers should trust
  339. his opinions.
  340.  
  341. List Manager
  342. ------------
  343. It’s very easy to be tempted by this part of the toolbox, along with
  344. the Dialog Manager.  The List Manager is a slow beast at times.  It
  345. also has some problems with “doing the right thing.”  I’ve found that
  346. the list will not be updated properly when the user clicks in a cell
  347. that is out of bounds.  LClick will return TRUE with a cell that
  348. doesn’t exists.  LActivate will erase the scrollbars instead of
  349. highlighting the properly.  Finally, the List Manager does not return
  350. errors.  How would a person know if LSetCell worked?
  351.  
  352. I’ve read and understood Tech Note 203, and have learned how to
  353. apply it.
  354.  
  355. Resource Manager
  356. ----------------
  357. I test all the handles being returned from the Resource Manager
  358. before using them, and if I get a NIL then I look at ResError.
  359. ResError sometimes lies and returns noErr and a NIL handle.  ResError
  360. is usually good for getting an error code AFTER you’ve already found
  361. an error.
  362.  
  363. Opening a resource file that is already open by another application
  364. is dangerous.  The Resource Manager will not tell you when you’ve done
  365. this.  There needs to be a OpenRFPerm that will return permission
  366. errors such as resFileBusyErr.  Refer to Tech Note 185.
  367.  
  368. When I or the Toolbox needs to get at one of my resources,
  369. CurResFile must be set to my application.  Also, look out for one
  370. particularly nasty situation when switching resource files.   If the
  371. segment loader goes for a CODE segment, it better be from our resource
  372. file!  The idea here is, in case you didn’t get it already, always
  373. have the current resource file be set to the application.  If a
  374. resource is needed from another file, switch momentarily to get the
  375. resource and immediately restore the current resource file to the
  376. application.  I take an added measure of defense and whenever I need a
  377. resource I use the Get1Resource calls.  These will only search the
  378. current resource file.
  379.  
  380. Strategies For Sound
  381. --------------------
  382. All of the Sound Manager code is contained in the SoundUnit.p.  This
  383. code was written to be general purpose, providing useful routines for
  384. other applications.  Lots of error checking is performed.  I’ve also
  385. extended the support for SndPlay and made it really asynchronous.
  386. I’ve demonstrated most of the abilities the present Sound Manager has
  387. to offer.  I will have to revise the SoundAppUnit to include any new
  388. features (e.g., multi channel support) when the next Sound Manager is
  389. released.
  390.  
  391. I allocate my own memory to be used as sound channels.  I allocate
  392. these pointers early in the application’s startup time to avoid memory
  393. fragmentation.  These channels are of the standard size (holding 128
  394. commands) but I’ve extended the structure to include my own
  395. information.  When I create a new sound channel, I pass it a pointer
  396. to this memory.  This will link in the 'snth' resource and hardware to
  397. my channel.  When I dispose of the channel, the Sound Manager will
  398. purge this resource and disconnect me from the hardware.  When adding
  399. the 'snth' resource, the Sound Manager will allocate a pointer into
  400. the application’s heap instead of the system’s.  This is a modifier
  401. stub used by the 'snth'.  This could cause some problems with memory
  402. management.  I create and dispose of all my channels as soon as
  403. possible, and this doesn’t cause me problems.
  404.  
  405. I keep track of which document is playing a sound, along with a
  406. global of when the application is playing sound.  I needed to keep
  407. track of which document is playing because if the user disposes of
  408. that document, I will have to stop playing the sound contained in it
  409. since the user wants to dispose of that data.  I keep track of when
  410. the application is playing sound in a global.  This is only used by
  411. the routine that calculates the sleep time for WaitNextEvent.
  412.  
  413. I came up with a pretty sick music notational system using Rez.
  414. Refer to the notes in the SoundAppSnds.r file.  If you’ve just
  415. finished a meal, wait four hours before reading.
  416.  
  417. The SoundUnit handles all of the Sound Manager code entirely.  This
  418. eliminates any and all references to the Sound Manager from the
  419. application.  The SoundUnit will return any error encountered while
  420. calling the Sound Manager, and does some extra error checking the
  421. Sound Manager doesn’t do.
  422.  
  423. The portion of the application that uses the wave table synthesizer
  424. is more complex than the other two.  I wanted to include an example
  425. channel modifier for use in the wave table channels.  This would have
  426. been a transpositional modifier that would take a given freqDurationCmd and
  427. transpose it by some amount.  This would be nice for the routine that
  428. plays a scale, by allowing the other three channels to be playing the
  429. same scale but at a different interval.  Unfortunately, I found that
  430. the Sound Manager has bugs using a modifier, at least with the wave
  431. table synths, and could not use them.
  432.  
  433. I’ve created a few wave table sounds and keep them in a 'snd '
  434. resource.  This allows me to change the sound of the wave table
  435. channels and not change any of the code.  Creating wave table data is
  436. complicated.  The example sounds I’ve included are samples I’ve taken
  437. from various sources.  I’ve cleaned them up quit a bit.  This was to
  438. set loop points, try and reduce clicks, correct the sample rates, and
  439. base frequencies.  This is also a complicated task.  Maybe I should document
  440. these techniques.
  441.  
  442. Jim Reekes E.O., Macintosh Developer Technical Support
  443. Sunday, August 7, 1994 7:06:41 PM
  444. */
  445. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  446. // global defines
  447.  
  448. // All of this code is for System 7 and later
  449. #define SystemSevenOrLater 1
  450.  
  451. // I don't use any obsolete stuff in the interfaces, and you shouldn't either.
  452. // You also need to worry about names because the Code Fragment Manager binds
  453. // system calls by name. Read the comments in ConditionalMacros.h
  454. #define OLDROUTINENAMES 0
  455.  
  456.  
  457. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  458. // includes
  459. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  460.  
  461. #include <AppleEvents.h>
  462. #include <Controls.h>
  463. #include <CursorCtl.h>
  464. #include <Devices.h>
  465. #include <DiskInit.h>
  466. #include <Dialogs.h>
  467. #include <Errors.h>
  468. #include <Events.h>
  469. #include <Files.h>
  470. #include <Icons.h>
  471. #include <Gestalt.h>
  472. #include <Lists.h>
  473. #include <LowMem.h>
  474. #include <Menus.h>
  475. #include <Memory.h>
  476. #include <QuickDraw.h>
  477. #include <Resources.h>
  478. #include <Scrap.h>
  479. #include <Script.h>
  480. #include <SegLoad.h>
  481. #include <StandardFile.h>
  482. #include <TextUtils.h>
  483. #include <ToolUtils.h>
  484. #include <Traps.h>
  485. #include <Types.h>
  486. #include <Windows.h>
  487.  
  488. #include <limits.h>
  489. #include <string.h>
  490.  
  491. #include <Sound.h>
  492. #include <SoundInput.h>
  493. #include "SoundUnit.h"
  494.  
  495. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  496. // constants
  497. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  498.  
  499. enum {
  500.     kOSTrapBit                = (1<<11),    /* bit 11 is the OS Trap bit */
  501.     kTrapNumberMask            = 0x07FF,    /* bits used by the A-Trap mechanism */
  502.  
  503.     kPollingSleepTime        = 60,        //MultiFinder’s sleep while sound is playing
  504.  
  505.     kNumberOfMasters        = 3,        //number of master pointer blocks we expect
  506.     kSizeOfReserve            = (unsigned long)32 * 1024, //size of reserve memory for grow zone proc
  507.     kMinSpace                = (unsigned long)32 * 1024, //minimum available memory I allow in heap
  508.     kMemForSndDoc            = 20 * 1024, //minimal amount of memory needed by document
  509.  
  510.     rAppSignature            = 'SAPP',    //applicaiton’s OS signature
  511.     rSndAppDocType            = 'sDoc',    //document's file type
  512.  
  513.     kScrollbarAdjust        = 16-1,        //the width of the scrollbar in the list
  514.     kListFrameInset            = -1,        //inset rectangle adjustment for list frame
  515.     kStadardWhiteSpacing    = 13,        //inset rectangle adjustment for dialog items
  516.  
  517.     kRecordTop                = 40,        //40,50 is topLeft for SndRecord dialog
  518.     kRecordLeft                = 50,        //40,50 is topLeft for SndRecord dialog
  519.  
  520.     kHiliteControlSelect    = 1,        //select the control
  521.     kHiliteControlDeselect    = 0,        //deselect the control
  522.     kCntlOn                    = 1,        //control’s value when truned on
  523.     kCntlOff                = 0,        //control’s value when truned off
  524.  
  525.     kWindowPosStartPt        = 2,        //offset from the topLeft of the screen
  526.     kWindowPosStaggerH        = 16,        //staggering amounts for new windows
  527.     kWindowPosStaggerV        = 3,        //not including the window’s title height
  528.  
  529.     kMinWindowTitleHeight    = 19,
  530.     kButtonFrameSize        = 3,        //button’s frame pen size
  531.     kButtonFrameInset        = -4,        //inset rectangle adjustment around button
  532.     kButtonSizeH            = 17,        //standard height of buttons
  533.     kDafaultButSizeH        = kButtonSizeH - kButtonFrameInset - kButtonFrameInset
  534. };
  535.  
  536. //refer to the SoundApp.r file for the explaination about these numbers
  537. enum {
  538.     kNumOfButtons            = 6,        //the number of buttons in the window
  539.     kSndButtonSizeW            = 100,        //SizeW of buttons in document window
  540.     kSndButtonSizeH            = 22,        //heigth of buttons in document window
  541.     kSoundWindowSizeH        = ((kNumOfButtons * (kStadardWhiteSpacing + kSndButtonSizeH))
  542.                                 + kStadardWhiteSpacing),
  543.     kSoundWindowSizeW        = 296,
  544.  
  545.     //standard position for icons in alerts
  546.     kIconWidthOrHeight        = 32,
  547.     kStdAlertIconTop        = kStadardWhiteSpacing,
  548.     kStdAlertIconLeft        = 23,
  549.     kStdAlertIconBottom        = kStdAlertIconTop + kIconWidthOrHeight,
  550.     kStdAlertIconRight        = kStdAlertIconLeft + kIconWidthOrHeight,
  551.  
  552.     kFSAsynch                = true,        //asynchronous File Manager call
  553.  
  554.     kEnterKey                = '\3',     //the keys I’m looking for
  555. #ifdef applec
  556.     kReturnKey                = '\n',        //MPW C is wrong, the return key is "\r" not "\n"
  557. #else
  558.     kReturnKey                = '\r',
  559. #endif
  560.     kEscape                    = '\33',
  561.     kUpArrow                = '\36',
  562.     kDownArrow                = '\37',
  563.     kPeriod                    = '.',
  564.     kBackspace                = '\b',
  565.  
  566. //This bit set in the ioFlAttrib field if the file’s resource fork is open.
  567.     kResForkOpenBit            = (1 << 2),
  568.  
  569. //For the delay time when flashing the menubar and highlighting a button.
  570.     kDelayTime                = 8,        //8/60ths of a second
  571.  
  572. //The minimal number of ticks the ShowWindow needs to be visible.
  573.     kShowTimeDelay            = 20,
  574.  
  575. //BUG NOTE: timbreCmd value of 255 on the Mac Plus/SE will cause a crash Sound Manager 1
  576.     kSquareWave                = 240,         //square wave for squareWaveSynth
  577.     kSineWave                = 0,        //sine wave for the squareWaveSynth
  578.     kPreferredTimbre        = 190,        //my preferred timbre for the squareWaveSynth
  579.  
  580. //Application snd resources must be higher than this number.
  581.     kSystemSndRange            = 8191        //This is the highest snd id reserved by Apple.
  582. };
  583.  
  584. //The following constants are the resource IDs.
  585. enum {
  586.     rMenuBar                = 1000,        //application’s menu bar
  587.  
  588.     rExitAlert                = 1000,        //emergency exit user alert
  589.     rUserAlert                = 1001,        //error message user alert
  590.     rSoundVolAlert            = 1002,        //sound is set low alert
  591.     rSaveAlert                = 1003,        //save changes? dialog
  592.  
  593.     rGetNameDLOG            = 2000,        //get a name for the sound dialog
  594.     rNameItem                = 3,        //edit text item in rGetNameDLOG
  595.     rUserItem                = 5,        //user item to help draw default outline
  596.  
  597.     rCustomGetFileDLOG        = 2001,        //dialog template for CustomGetFile
  598.     rSndOnlyCheckBox        = 10        //dialog item number in CustomGetFile
  599. };
  600.  
  601. /*
  602. These are the window IDs used in the applications.  Each one must be unique,
  603. since they are used to identify which window the event took place in.
  604. */
  605. enum{
  606.     rAboutWindow            = 1000,        //about window
  607.     rStatusWindow            = 1001,        //sound status window
  608.     rSoundWindow            = 1002,        //sound document window
  609.  
  610.     rListRectID                = 1000,        //resource containing size of list rectangle
  611.  
  612.     rCancelCntl                = 1000,        //stop button ID for the status window
  613.     rPlaySndCntl            = 1001,        //sound button IDs for the sound document window
  614.     rHyperPlayCntl            = 1002,
  615.     rPlayScaleCntl            = 1003,
  616.     rMelodyCntl                = 1004,
  617.     rStopCntl                = 1005,
  618.     rRecordCntl                = 1006,
  619.     rAboutOkCntl            = 1007,
  620.     rUntitled                = 1000,        //string ID for untitled resources
  621.     rAboutText                = 1001,        //string ID for text appearing in about window
  622.     rPutFileMsg                = 1002,        //string for text appearing in SFPutFile dialog
  623.     rMoofIcon                = 1000,        //resource ID for ICON of application
  624.     rAppPict                = 1000,        //resource ID of picture shown in about window
  625.     rSndCursor                = 1000        //cursor resource for our documents
  626. };
  627.  
  628. /*
  629. The following are the snd resource IDs contained in the application,
  630. which start at ID 9000.  IDs 0 - 8191 are reserved for Apple.
  631. */
  632. enum {
  633.     rMoofSound                = 9000,        //snd for the about window
  634.     rScaleSnd                = 9001,        //snd containing a scale
  635.     rMelodyPart1            = 9002,        //snd containing a melody
  636.     rMelodyPart2            = 9003,        //snd containing the harmony
  637.     rMelodyPart3            = 9004,        //snd containing the harmony
  638.     rMelodyPart4            = 9005,        //snd containing the harmony
  639.     rWaveHarmony            = 9006,        //snd containing waveTable for harmony
  640.     rWaveMelody                = 9007,        //snd containing waveTable for melody
  641.     rCounterPt1                = 9008,        //snd containing soprano part of counter point
  642.     rCounterPt2                = 9009,        //snd containing alto part of counter point
  643.     rCounterPt3                = 9010,        //snd containing tenor part of counter point
  644.     rCounterPt4                = 9011,        //snd containing bass part of counter point
  645.     rSopranoVox                = 9012,        //snd containing waveTable of soprano voice
  646.     rAltoVox                = 9013,        //snd containing waveTable of alto voice
  647.     rTenorVox                = 9014,        //snd containing waveTable of tenor voice
  648.     rBassVox                = 9015,        //snd containing waveTable of bass voice
  649.  
  650.     rSampleHarmony            = 9016,        //snd containing the sampled sound harmony
  651.     rSampleMelody            = 9017        //snd containing the sampled sound melody
  652. };
  653.  
  654. //The following are resource IDs for messages.
  655. enum {
  656.     sErrStrings                = 1000,        //error string STR# ID
  657.     sStandardErr            = 1,        //An error has occurred.
  658.     sMemErr                    = 2,        //A Memory Manager error has occurred.
  659.     sResErr                    = 3,        //A Resource Manager error has occurred.
  660.     sCurInUseErr            = 4,        //That file is currently in use.
  661.     sWavesBroken            = 5,        //The wave table synthesizer is not available.
  662.     sWrongVersion            = 6,        //This system does not support the Sound Manager...
  663.     sLowMemory                = 7,        //Memory is too low to continue...
  664.     sNoMenus                = 8,        //Could not find application’s menu resources.
  665.     sInitSoundErr            = 9,        //Could not initialize the SoundUnit.
  666.     sSoundErr                = 10,        //The Sound Manager has encountered an error.
  667.     sNewDocErr                = 11,        //Could not create a new document.
  668.     sInitStatusErr            = 12,        //Error initializing the status window.
  669.     sEditErr                = 13,        //Could not complete the edit command.
  670.     sDocErr                    = 14,        //There is a problem with this document.
  671.  
  672.     sMsgStrings                = 1001,        //message string STR# ID
  673.     sPlayingMsg                = 1,        //playing a sound
  674.     sHyperMsg                = 2,        //playing a sound the Hyper way
  675.     sScaleMsg                = 3,        //playing scale
  676.     sMelodyMsg                = 4,        //playing melody
  677.     sTimbresMsg                = 5,        //playing various timbres
  678.     sCounterPtMsg            = 6,        //playing 4 part counter point
  679.  
  680.     sSMErrStrings            = 1002        //strings describing Sound Manager errors
  681. };
  682.  
  683. /*
  684. The following constants are used to identify menus and items. The menu IDs
  685. have an “m” prefix and the item numbers within each menu have an “i” prefix.
  686. */
  687.  
  688. enum {
  689.     mApple                    = 128,        //Apple menu and items
  690.     iAbout                    = 1,
  691.  
  692.     mFile                    = 129,        //File menu and items
  693.     iNew                    = 1,
  694.     iOpen                    = 2,
  695.     iClose                    = 4,
  696.     iQuit                    = 12,
  697.  
  698.     mEdit                    = 130,        //Edit menu and items
  699.     iUndo                    = 1,
  700.     iCut                    = 3,
  701.     iCopy                    = 4,
  702.     iPaste                    = 5,
  703.     iClear                    = 6,
  704.  
  705.     mDemos                    = 1000,        //Demos menu and items
  706.     iCheckVolume            = 1,
  707.     iSquareScale            = 3,
  708.     iSquareMelody            = 4,
  709.     iSquareTimbre            = 5,
  710.     iWaveScale                = 7,
  711.     iWaveMelody                = 8,
  712.     iWaveSATB                = 9,
  713.     iSampleMelody            = 11,
  714.     iSampleSATB                = 12
  715. };
  716.  
  717.  
  718. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  719. // macros
  720. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  721.  
  722. // Define HighWord and LowWord macros for efficiency.
  723. #define HighWord(aLong)        ((aLong) >> 16)
  724. #define LowWord(aLong)        ((aLong) & 0x0000FFFF)
  725.  
  726. // accessing a rectangle's points
  727. #define TopLeft(r)            (* (Point *) &(r).top)
  728. #define BottomRight(r)        (* (Point *) &(r).bottom)
  729.  
  730. #define AbsoluteValue(n)    ((n > 0) ? n : -n)
  731.  
  732. #if GENERATINGCFM
  733. #define CreateRoutineDescriptor(info, proc)                                    \
  734.  RoutineDescriptor g##proc##RD = BUILD_ROUTINE_DESCRIPTOR(info, proc)
  735.  
  736. #define GetRoutineAddress(proc)    (&g##proc##RD)
  737.  
  738. #else
  739. #define GetRoutineAddress(proc)    proc
  740. #endif
  741.  
  742. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  743. // types
  744. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  745.  
  746. typedef RectPtr *RectHandle;
  747.  
  748. /*
  749. This is a document layout that contains the window record and references
  750. to the associating data.  The window record MUST be the first field.  This
  751. is because I use the window pointer returned by the Toolbox to be a
  752. pointer to my document.  To confirm that the window pointer is a document
  753. pointer, I store an application reference in the window record’s refCon.
  754. Then, I use a routine to test for the presence of this reference to insure
  755. I’m looking at one of my document’s windows.
  756. */
  757.  
  758. struct SndDocument {
  759.     WindowRecord    window;                // must be first field
  760.     short             resFile;            // document’s resource file
  761.     short             vRefNum;
  762.     long             dirID;
  763.     ListHandle        list;                // document’s list of sounds
  764.     Boolean            sndInUse;            // document is using a 'snd ' resource
  765. };
  766. typedef struct SndDocument SndDocument;
  767. typedef SndDocument *SndDocPeek;        // to peek at the document record
  768.  
  769. // This is the status window layout.  The concept here is similar to the
  770. // document type mentioned above.  The message is a string handle used to
  771. // store the current message.
  772.  
  773. struct StatusWindow {
  774.     WindowRecord    window;
  775.     StringHandle    message;            // current text of status message
  776.     long            showTime;            // time window was shown
  777. };
  778. typedef struct StatusWindow StatusWindow;
  779. typedef StatusWindow *StatWindowPeek;
  780.  
  781. // This is the about window layout.  The concept here is similar to the
  782. // document type mentioned above.  The comment is a string handle used to
  783. // store the current message.
  784.  
  785. struct AboutWindow {
  786.     WindowRecord    window;
  787.     Handle            appPict;            // handle to picture of app’s name
  788.     Handle             comment;            // handle to string of about comments
  789. };
  790. typedef struct AboutWindow AboutWindow;
  791. typedef AboutWindow *AboutWPeek;
  792.  
  793. // This is the template to the WIND resource.  I used it to load in the WIND
  794. // resource and then adjust the boundsRect.  I also look at the procID to
  795. // determine if it has a title bar or drag region.
  796.  
  797. struct WindowTemplate {                    // template to a WIND resource
  798.     Rect        boundsRect;
  799.     short        procID;
  800.     Boolean        visible;
  801.     Boolean        filler1;
  802.     Boolean        goAwayFlag;
  803.     Boolean        filler2;
  804.     long        refCon;
  805.     Str255        title;
  806. };
  807. typedef struct WindowTemplate WindowTemplate;
  808. typedef WindowTemplate *WindowTPtr, **WindowTHndl;
  809.  
  810. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  811. // inlines
  812. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  813.  
  814. /*
  815. This is a handy routine to copy pascal strings. It's smaller than the
  816. library call pstrcopy, and faster too.
  817. */
  818.  
  819. #if GENERATING68K
  820. #pragma parameter PStringCopy(__A0,__A1)
  821. void PStringCopy(StringPtr source, StringPtr destination)
  822.  FIVEWORDINLINE (0x7000, 0x1010, 0x12D8, 0x51C8, 0xFFFC);
  823. //                    moveq    #0,d0
  824. //                    move.b    (a0),d0
  825. //            loop    move.b    (a0)+,(a1)+
  826. //                    dbra    d0,loop
  827. #else
  828. #define PStringCopy(source, dest) strncpy(dest, source, StrLength(source) + 1)
  829. #endif
  830.  
  831. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  832. // prototypes
  833. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  834.  
  835. short NumToolboxTraps(void);
  836. Boolean TrapExists(short theTrap);
  837. pascal long MyGrowZone(Size cbNeeded);
  838. Boolean LowOnReserve(void);
  839. void RecoverReserve(void);
  840. Boolean AllocateReserve(void);
  841. Boolean FailLowMemory(long memRequest);
  842. Boolean HasSelection(SndDocPeek sndDoc);
  843. OSErr GetSelection(SndDocPeek sndDoc, SndListHandle *sndHandle);
  844. void SelectNextCell(ListHandle list, Boolean next);
  845. void SelectSndCell(SndDocPeek sndDoc, short resID);
  846. OSErr InitSndList(SndDocPeek docPtr);
  847. Boolean OpenByApp(FSSpecPtr file, WindowPtr *window);
  848. Point GetGlobalMouse(void);
  849. short GetWTitleHeight(short variant);
  850. Point GetGlobalTopLeft(WindowPtr window);
  851. void MyParamText(StringHandle text, StringPtr cite0, StringPtr cite1);
  852. void CenterWindowRect(short variant, Rect *theRect);
  853. WindowPtr GetCenteredWindow(short id, Ptr p, WindowPtr behind);
  854. short CenteredAlert(short alertID);
  855. DialogPtr GetCenteredDialog(short id, Ptr p, WindowPtr behind);
  856. void DoButtonOutline(ControlHandle button);
  857. void SelectButton(ControlHandle button);
  858. void ActivateSndCntls(SndDocPeek sndDoc);
  859. Boolean IsDAWindow(WindowPtr window);
  860. Boolean IsDocWindow(WindowPtr window);
  861. Boolean IsModalWindow(WindowPtr window);
  862. void KillSound(void);
  863. Boolean DoCloseWindow(WindowPtr window);
  864. void AlertUser(short error, short messageID);
  865. void EmergencyExit(short message);
  866. void Terminate(void);
  867. void DrawStatusWindow(void);
  868. void ShowStatusWindow(short messageID);
  869. void InitStatusWindow(void);
  870. pascal void DoErrorSound(short soundNo);
  871. void CheckSoundVolume(void);
  872. void AddSndDocControls(WindowPtr window);
  873. Boolean PositionAvailable(Point newPt, short wTitleHeight);
  874. WindowPtr NewStackedWindow(short windID, Ptr windStorage);
  875. OSErr CreateSoundDoc(short resRef, FSSpecPtr file);
  876. void OpenSoundDoc(FSSpecPtr file);
  877. void NewSoundDoc(void);
  878. pascal Boolean SFFilter(CInfoPBPtr p, Boolean *sndFilesOnly);
  879. pascal short SFGetHook(short mySFItem, DialogPtr dialog, void *sndFilesOnly);
  880. void GetSoundDoc(void);
  881. void DrawAboutWindow(WindowPtr window);
  882. void DoAbout(void);
  883. void PlaySelectedSnd(SndDocPeek sndDoc, short message);
  884. void PlaySndSong(SndDocPeek sndDoc, short sndID);
  885. void PlaySquareSong(short sndID);
  886. void PlaySquareTimbres(void);
  887. void PlayWaveScale(void);
  888. OSErr GetSndSongs(short sndSongID1, short sndSongID2, short sndSongID3, short sndSongID4, SndListHandle *sndSong1, SndListHandle *sndSong2, SndListHandle *sndSong3, SndListHandle *sndSong4);
  889. OSErr InstallWaveSnds(SndChannelPtr chan1, SndChannelPtr chan2, SndChannelPtr chan3, SndChannelPtr chan4, short waveID1, short waveID2, short waveID3, short waveID4);
  890. void PlayWaveMelody(void);
  891. void PlayWaveSATB(void);
  892. void PlaySampleMelody(void);
  893. void PlaySampleSATB(void);
  894. pascal void DefaultOutline(WindowPtr window, short theItem);
  895. void GetSndName(Str255 sndName);
  896. OSErr AddSnd(SndDocPeek sndDoc, StringPtr sndNamePtr, SndListHandle sndHndl);
  897. void ClearSnd(SndDocPeek sndDoc);
  898. void DoRecordSound(SndDocPeek sndDoc);
  899. void AdjustMenus(void);
  900. void CopySnd(SndDocPeek sndDoc);
  901. void CutSnd(SndDocPeek sndDoc);
  902. void PasteSnd(SndDocPeek sndDoc);
  903. void DoMenuCommand(long menuResult);
  904. void DrawSndWindow(WindowPtr window);
  905. void DoKeyDown(char key, WindowPtr window);
  906. Boolean ListClick(SndDocPeek sndDoc, EventRecord *event);
  907. void DoSndDocClick(SndDocPeek sndDoc, EventRecord *event);
  908. void DoStatClick(StatWindowPeek statWindow, EventRecord *event);
  909. void DoAboutClick(WindowPtr window, EventRecord *event);
  910. void DoUpdate(WindowPtr window);
  911. void DoActivate(WindowPtr window, Boolean becomingActive);
  912. pascal OSErr QuitApplicationEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon);
  913. pascal OSErr OpenDocumentsEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon);
  914. pascal OSErr PrintDocumentsEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon);
  915. pascal OSErr OpenApplicationEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon);
  916. void DoEvent(EventRecord *event);
  917. void AdjustCursor(RgnHandle region);
  918. void EventLoop(void);
  919. void Initialize(void);
  920. void main(void);
  921.  
  922. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  923. // Globals (The “g” prefix is used to emphasize that a variable is global.)
  924. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  925.  
  926. /*
  927. gMac is used to hold the result of a SysEnvirons call. This makes it
  928. convenient for any routine to check the environment. It is considered
  929. global information, anyway.
  930. */
  931.  
  932.     SysEnvRec gMac;                    //set up by Initialize
  933.  
  934. /*
  935. gReserveMemory is a handle of reserve memory used by my grow zone
  936. procedure.  If memory is attempted to be allocated and fails, my grow
  937. zone will release this reserved block of memory.
  938. */
  939.  
  940.     Handle gReserveMemory;
  941.  
  942. /*
  943. gStatusWindow is the window that tells the user what’s happening.  I show
  944. it while a sound is playing, and remove it as soon as the sound is
  945. complete.  It is initialized once during startup, and from then on two
  946. routines are used to show and hide it.  This demonstrates orchestrating
  947. multimedia, that sound/graphic idea, at least in a crude sort of way.
  948. */
  949.  
  950.     StatWindowPeek gStatusWindow;
  951.  
  952. /*
  953. gAppResRef is the application’s resource file reference.  I need to save
  954. this since I can open other resource files.  The current resource file is
  955. always gAppResRef unless I momentarily set it to another file to read its
  956. resources, and then immediately restore it back.
  957. */
  958.  
  959.     short gAppResRef;                //set up by Initialize
  960.  
  961. /*
  962. gInBackground is maintained by our osEvent handling routines. Any part of
  963. the program can check it to find out if it is currently in the background.
  964. */
  965.  
  966.     Boolean gInBackground;            //maintained by Initialize and DoEvent
  967.  
  968. /*
  969. We have to allocate our own QuickDraw globals when creating code for PowerMacs.
  970. MetroWerks declares "qd" in their runtime, so don't do that twice.
  971. */
  972.  
  973. #if GENERATINGCFM && !defined(__MWERKS__)
  974.     QDGlobals    qd;
  975. #endif
  976.  
  977. /*
  978. This is necessary because of the Apple Event Manager. We used to be able
  979. to quit directly when the user choose Quit from the File menu. But because
  980. of the design of Apple Events, we cannot call ExitToShell from the quit handler.
  981. That event handler must set a flag and then check it in the event loop.
  982. */
  983.  
  984.     Boolean gTerminate;
  985.  
  986.  
  987. // allocate the RoutineDescriptors for Power Mac toolbox calls
  988. #if GENERATINGCFM
  989. CreateRoutineDescriptor(uppGrowZoneProcInfo, MyGrowZone);
  990. CreateRoutineDescriptor(uppFileFilterYDProcInfo, SFFilter);
  991. CreateRoutineDescriptor(uppDlgHookYDProcInfo, SFGetHook);
  992. CreateRoutineDescriptor(uppUserItemProcInfo, DefaultOutline);
  993. CreateRoutineDescriptor(uppUserItemProcInfo, QuitApplicationEvent);
  994. CreateRoutineDescriptor(uppUserItemProcInfo, OpenDocumentsEvent);
  995. CreateRoutineDescriptor(uppUserItemProcInfo, PrintDocumentsEvent);
  996. CreateRoutineDescriptor(uppUserItemProcInfo, OpenApplicationEvent);
  997. #endif
  998.  
  999. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1000. // IMPLEMENTATION
  1001. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1002.  
  1003. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1004. /*
  1005. InitGraf is always implemented (trap 0xA86E). If the trap table is big
  1006. enough, trap 0xAA6E will always point to either Unimplemented or some other
  1007. trap, but will never be the same as InitGraf. Thus, you can check the size
  1008. of the trap table by asking if the address of trap 0xA86E is the same as 0xAA6E.
  1009. */
  1010.  
  1011. #pragma segment Initialize
  1012. short NumToolboxTraps(void)
  1013. {
  1014.     if ( GetToolboxTrapAddress(_InitGraf) == GetToolboxTrapAddress(_InitGraf + 0x0200) )
  1015.         return (0x0200);
  1016.     else
  1017.         return (0x0400);
  1018. }
  1019.  
  1020. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1021. /*
  1022. Check to see if a given trap is implemented.  GetTrapAddress may screw up and
  1023. wrap around into the trap table if you give it a toolbox trap that is out of
  1024. range, so check for this first.
  1025. */
  1026.  
  1027. #pragma segment Initialize
  1028. Boolean TrapExists(short theTrap)
  1029. {
  1030.     UniversalProcPtr    trapAddress;
  1031.  
  1032.     if ( !(theTrap & kOSTrapBit) )                        // is this an OS trap?
  1033.         trapAddress = GetOSTrapAddress(theTrap);
  1034.     else {                                                // no, this is a tool trap
  1035.         theTrap &= kTrapNumberMask;                        // get the trap number
  1036.         if ( theTrap < NumToolboxTraps() )                // can this tool trap exist?
  1037.             trapAddress = GetToolTrapAddress(theTrap);
  1038.         else
  1039.             return (false);
  1040.     }
  1041.     return ( GetToolboxTrapAddress(_Unimplemented) != trapAddress );
  1042. }
  1043.  
  1044. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1045. /*
  1046. This is a very basic grow zone procedure.  My application keeps a reserve
  1047. handle of memory in case the Memory Manager gets a request for some memory
  1048. that is not available in my heap.  If memory were to get tight (<32k),
  1049. the Toolbox will crash the system, especially Quickdraw.  Before releasing
  1050. the reserve handle I make sure it isn’t the GZSaveHnd.  This handle cannot
  1051. be touched by the grow zone procedure.
  1052.  
  1053. WARNING:  The grow zone procedure will be called and A5 may not be valid.
  1054. Read Tech Note #136 and 208
  1055. */
  1056.  
  1057. #pragma segment Main
  1058. pascal long MyGrowZone(Size cbNeeded)
  1059. {
  1060. #pragma unused (cbNeeded)
  1061.     long theA5;
  1062.     long result;
  1063.  
  1064.     theA5= SetCurrentA5();
  1065.     if (((*gReserveMemory) != nil) && (gReserveMemory != GZSaveHnd())) {
  1066.         EmptyHandle(gReserveMemory);
  1067.         result = kSizeOfReserve;                    //released this much memory
  1068.     } else
  1069.         result = 0;                                //this may release more memory
  1070.     theA5= SetA5(theA5);
  1071.     return(result);
  1072. }
  1073.  
  1074. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1075. /*
  1076. Before my application attempts to use more memory, I call this routine
  1077. to check if I’m already using my reserve memory.  If so, then I better
  1078. prepare to die or get my reserve back.
  1079. */
  1080.  
  1081. #pragma segment Main
  1082. Boolean LowOnReserve(void)
  1083. {
  1084.     return((*gReserveMemory) == nil);        // empty handle is low reserve
  1085. }
  1086.  
  1087. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1088. /*
  1089. This is called from the event loop if LowOnReserve returns that I’m out of
  1090. the reserve memory.  This will recover the reserve memory block.  If this
  1091. fails, it will be called the next time through the event loop.
  1092. */
  1093.  
  1094. #pragma segment Main
  1095. void RecoverReserve(void)
  1096. {
  1097.     ReallocateHandle(gReserveMemory, kSizeOfReserve);
  1098. }
  1099.  
  1100. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1101. /*
  1102. This is called at startup time to allocate the reserve memory block used
  1103. in the grow zone procedure.  If I’m unable to obtain this reserve, then
  1104. return false to signal a failure.
  1105. */
  1106.  
  1107. #pragma segment Initialize
  1108. Boolean AllocateReserve(void)
  1109. {
  1110.     gReserveMemory = NewHandle(kSizeOfReserve);
  1111.     return(gReserveMemory != nil);
  1112. }
  1113.  
  1114. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1115. /*
  1116. Call PurgeSpace and see if the requested amount of memory exists in the
  1117. heap including a minimal amount of heap space.  Also, if my grow zone’s
  1118. reserve has been release, that’s considered a failure.  I don’t perform
  1119. any purging here.  The Memory Manager will do this if it needs the space.
  1120. This routine can be called with a memRequest == 0.  This checks if the heap
  1121. space is getting critical.
  1122. */
  1123.  
  1124. #pragma segment Main
  1125. Boolean FailLowMemory(long memRequest)
  1126. {
  1127.     long    total;
  1128.     long    contig;
  1129.  
  1130.     PurgeSpace(&total, &contig);
  1131.     return((total < (memRequest + kMinSpace)) || LowOnReserve());
  1132. }
  1133.  
  1134. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1135. /*
  1136. This a simple test to see if the user has a currently selected list item.
  1137. */
  1138.  
  1139. #pragma segment Main
  1140. Boolean HasSelection(SndDocPeek sndDoc)
  1141. {
  1142.     Cell aCell;
  1143.  
  1144.     SetPt(&aCell, 0, 0);
  1145.     return(LGetSelect(true, &aCell, sndDoc->list));
  1146. }
  1147.  
  1148. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1149. /*
  1150. Given a document, this will find the currently selected cell in the list.
  1151. Then using this cell as an index number, I call Get1IndResource.  This
  1152. will return the proper handle.  Since the List Manager is zero based and
  1153. the Resource Manager isn’t, I have to add one to the index.
  1154.  
  1155. BUG NOTE: GetIndResource will return a bogus handle if the index is not
  1156. positive.
  1157. */
  1158.  
  1159. #pragma segment Main
  1160. OSErr GetSelection(SndDocPeek sndDoc, SndListHandle *sndHandle)
  1161. {
  1162.     Cell    aCell;
  1163.     OSErr    result;
  1164.  
  1165.     result = noErr;
  1166.     SetPt(&aCell, 0, 0);
  1167.     if (LGetSelect(true, &aCell, sndDoc->list)) {
  1168.         if (aCell.v > -1) {                        // GetIndResource doesn’t like < 0
  1169.             UseResFile(sndDoc->resFile);        // only get our resources
  1170.             *sndHandle = (SndListHandle)Get1IndResource(soundListRsrc, aCell.v + 1);
  1171.             if (*sndHandle == nil)
  1172.                 result = ResError();            // return any error
  1173.             UseResFile(gAppResRef);                // restore our resource file
  1174.         }
  1175.     }
  1176.     return(result);
  1177. }
  1178.  
  1179. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1180. /*
  1181. This is used to allow the user to select items from the list by using
  1182. the arrow keys.  Given a list and the direction, this will select the
  1183. next cell.  It will do nothing if we’re at the first cell and the user
  1184. wants to do even higher (sped), or if we’re at the last cell and the
  1185. user wants to go even lower (rent a clue bud).
  1186. */
  1187.  
  1188. #pragma segment Main
  1189. void SelectNextCell(ListHandle list, Boolean next)
  1190. {
  1191.     Cell    aCell;
  1192.     short    lastItem;
  1193.  
  1194.     lastItem = (**list).dataBounds.bottom - 1;        // bounds is 1 greater
  1195.     SetPt(&aCell, 0, 0);
  1196.     if (LGetSelect(true, &aCell, list)) {
  1197.         if ((next && (aCell.v < lastItem)) || ((!next) && (aCell.v > 0))) {
  1198.             LSetSelect(false, aCell, list);
  1199.             if (next)
  1200.                 aCell.v = aCell.v + 1;
  1201.             else
  1202.                 aCell.v = aCell.v - 1;
  1203.             SetPt(&aCell, aCell.h, aCell.v);
  1204.             LSetSelect(true, aCell, list);
  1205.             LAutoScroll(list);
  1206.         }
  1207.     }
  1208.     else                                            // if no cells selected...
  1209.         LSetSelect(true, aCell, list);                // select the first cell
  1210. }
  1211.  
  1212. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1213. /*
  1214. VERSION 1.1:  This routine will go through the list of snd resources
  1215. looking for the one that has the resource ID matching the parameter passed
  1216. in.  First thing to do is deselect the current selection.  Then once the
  1217. matching resource is found, select that one and scroll it into view.  One
  1218. assumption made is that the resources and the list are both index in the
  1219. same order.  This is true for the sndDoc, since I built the list this way.
  1220. */
  1221.  
  1222. #pragma segment Main
  1223. void SelectSndCell(SndDocPeek sndDoc, short resID)
  1224. {
  1225.     Str255 name;
  1226.     Cell aCell;
  1227.     Handle sndHndle;
  1228.     ResType rType;
  1229.     short testID;
  1230.     short index;
  1231.     short numSnd;
  1232.  
  1233.     index = 0;
  1234.     aCell.h = 0;
  1235.     aCell.v = 0;
  1236.     if (LGetSelect(true, &aCell, sndDoc->list))
  1237.         LSetSelect(false, aCell, sndDoc->list); //deselect any cell
  1238.     UseResFile(sndDoc->resFile);                //count only its resources
  1239.     numSnd = Count1Resources(soundListRsrc);    //number of sounds available
  1240.     do {
  1241.         index++;
  1242.         SetResLoad(false);                        //don’t load any resources
  1243.         sndHndle = Get1IndResource(soundListRsrc, index); //only get snd from file
  1244.         SetResLoad(true);                            //back to normal resource operations
  1245.         GetResInfo(sndHndle, &testID, &rType, name);
  1246.     } while ((resID != testID) && (index < numSnd));
  1247.  
  1248.     UseResFile(gAppResRef);                        //restore our resource file
  1249.     aCell.h = 0;
  1250.     aCell.v = index - 1;
  1251.     LSetSelect(true, aCell, sndDoc->list);
  1252.     LAutoScroll(sndDoc->list);
  1253. }
  1254.  
  1255. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1256. /*
  1257. This is used to create the list showing all the snd resources in the file.
  1258. If anything goes wrong while attempting to get any of the resources, then I
  1259. return false.  I don’t want the document to continue if something goes
  1260. wrong while reading a resource.  If I do get the resource, then I add its
  1261. name to the list in a new row.  I’m assured that at least one resource is
  1262. in the file before this routine is called.  Untitled resources will get one.
  1263. */
  1264.  
  1265. #pragma segment Open
  1266. OSErr InitSndList(SndDocPeek docPtr)
  1267. {
  1268.     short            index;
  1269.     short            resID;
  1270.     short            newRow;
  1271.     short            numSnd;
  1272.     Handle            resHandle;
  1273.     StringHandle    strHandle;
  1274.     ResType            itsType;
  1275.     Str255            resName;
  1276.     Str255            untitled;
  1277.     Cell            aCell;
  1278.     OSErr            result = noErr;
  1279.  
  1280.     strHandle = (StringHandle)Get1Resource('STR ', rUntitled);
  1281.     if (strHandle != nil)
  1282.         PStringCopy(*strHandle, untitled);        // save no name title
  1283.     else
  1284.         untitled[0] = 0;                        // at least an empty string
  1285.     UseResFile(docPtr->resFile);
  1286.     numSnd = Count1Resources(soundListRsrc);
  1287.     newRow = LAddRow(numSnd, 0, docPtr->list);
  1288.     for (index = 1; index <= numSnd; index++) {
  1289.         SetResLoad(false);                        // don’t load any resources
  1290.         resHandle = Get1IndResource(soundListRsrc, index); // only get snd from file
  1291.         SetResLoad(true);                        // back to normal operations
  1292.         if (resHandle != nil) {                    // only if I got the snd
  1293.             GetResInfo(resHandle, &resID, &itsType, resName);
  1294.             if (StrLength(resName) == 0)        // if the snd isn’t named...
  1295.                 PStringCopy(untitled, resName);    // give it a name
  1296.             SetPt(&aCell, 0, index - 1);
  1297.             LSetCell(&resName[1], StrLength(resName), aCell, docPtr->list);
  1298.         }
  1299.         else {                                     // resHandle == NIL
  1300.             result = resNotFound;                // problem with resource file
  1301.             break;                                // get out of the loop
  1302.         }
  1303.     }
  1304.     UseResFile(gAppResRef);                        // restore our resource file
  1305.     return(result);
  1306. }
  1307.  
  1308. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1309. /*
  1310. In the case that the user has attempted to open a resource file that is
  1311. already open, this routine will scan my open documents for it.  If I find
  1312. that the requested file is already open by the application, then return
  1313. true and its window pointer.  The application can then simply select that
  1314. window.  If the resource file is open but not by this application, that’s
  1315. a problem and I don’t use the resource file.  Many problems with using an
  1316. open resource file.  Now if the Resource Manager would take care of this
  1317. problem for us...
  1318. */
  1319.  
  1320. #pragma segment Open
  1321. Boolean OpenByApp(FSSpecPtr file, WindowPtr *window)
  1322. {
  1323.     Str255 docName;
  1324.     WindowPtr testWindow;
  1325.     Boolean result;
  1326.  
  1327.     result = false;
  1328.     testWindow = FrontWindow();
  1329.     while (testWindow != nil) {
  1330.         if (GetWRefCon(testWindow) == rSoundWindow)
  1331.             if ((file->vRefNum == ((SndDocPeek)testWindow)->vRefNum)
  1332.                 && (file->parID == ((SndDocPeek)testWindow)->dirID))
  1333.             {
  1334.                 GetWTitle(testWindow, docName);
  1335.                 if (EqualString(file->name, docName, false, true))
  1336.                 {
  1337.                     *window = testWindow;
  1338.                     result = true;
  1339.                     break;
  1340.                 }
  1341.             }
  1342.         testWindow = (WindowPtr)(((WindowPeek)testWindow)->nextWindow);
  1343.     }
  1344.     return(result);
  1345. }
  1346.  
  1347. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1348. /*
  1349. Get the global coordinates of the mouse.  Get the global coordinates by
  1350. calling GetMouse and LocalToGlobal.  This assumes the current port is a
  1351. valid graf port.  When wouldn’t it be?
  1352. */
  1353.  
  1354. #pragma segment Main
  1355. Point GetGlobalMouse(void)
  1356. {
  1357.     Point globalPt;
  1358.  
  1359.     GetMouse(&globalPt);
  1360.     LocalToGlobal(&globalPt);
  1361.     return(globalPt);
  1362. }
  1363.  
  1364. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1365. /*
  1366. Try and determine the window’s title bar height.  This isn’t easy,
  1367. especially if the window is invisible.  We all know how the standard Apple
  1368. System WDEF works, at least at this date we do.  I assume that method as
  1369. shown below.  I could do what MacApp does with the Function CallWDefProc.
  1370. If the user has installed a replacement for the System WDEF, then it’s
  1371. their problem to deal with.  My method will work as long as Apple doesn’t
  1372. change how the WDEF in System 6.0 calculates the title bar height.  This
  1373. will allow my application to work on international Macs that have a larger
  1374. system font than Chicago.  I check the window’s variant code for one that
  1375. includes a title bar.  I will have to change this routine to adjust for
  1376. the modal-moveable window type, which hasn’t been defined yet.
  1377.  
  1378. In this routine, I violate my rule about not using the GetPort, SetPort,
  1379. SetPort sequence mentioned at the start of the file. Mostly, I do this
  1380. because it’s not all that apparent that a routine called GetWTitleHeight
  1381. will change the port, so I make sure that it doesn’t.
  1382. */
  1383.  
  1384. #pragma segment Open
  1385. short GetWTitleHeight(short variant)
  1386. {
  1387.     FontInfo info;
  1388.     GrafPtr curGraf;
  1389.     GrafPtr wMgrPort;
  1390.     short wTitleHeight;
  1391.     short result;
  1392.  
  1393.     if (    (variant == documentProc)
  1394.          || (variant == noGrowDocProc)
  1395.          || (variant == zoomDocProc)
  1396.          || (variant == rDocProc) )
  1397.     {
  1398.         GetPort(&curGraf);
  1399.         GetWMgrPort(&wMgrPort);                        //I need to know the font...
  1400.         SetPort(wMgrPort);                            //info in the System’s port
  1401.         GetFontInfo(&info);
  1402.         SetPort(curGraf);                            //restore current port
  1403.         wTitleHeight = info.ascent + info.descent + info.leading + 2;
  1404.         if (wTitleHeight < kMinWindowTitleHeight)
  1405.             wTitleHeight = kMinWindowTitleHeight;
  1406.         result = wTitleHeight;
  1407.     } else
  1408.         result = 0;                            //other window types have no title
  1409.     return(result);
  1410. }
  1411.  
  1412. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1413. /*
  1414. Given a window, this will return the top left point of the window’s
  1415. port in global coordinates.  Something this doesn’t include, is the
  1416. window’s drag region (or title bar).  This returns the top left point
  1417. of the window’s content area only.
  1418.  
  1419. In this routine, I violate my rule about not using the GetPort, SetPort,
  1420. SetPort sequence mentioned at the start of the file. Mostly, I do this
  1421. because it’s not all that apparent that a routine called GetGlobalTopLeft
  1422. will change the port, so I make sure that it doesn’t.
  1423. */
  1424.  
  1425. #pragma segment Main
  1426. Point GetGlobalTopLeft(WindowPtr window)
  1427. {
  1428.     GrafPtr theGraf;
  1429.     Point globalPt;
  1430.  
  1431.     GetPort(&theGraf);
  1432.     SetPort(window);
  1433.     globalPt = TopLeft(window->portRect);
  1434.     LocalToGlobal(&globalPt);
  1435.     SetPort(theGraf);
  1436.     return(globalPt);
  1437. }
  1438.  
  1439. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1440. /*
  1441. I’m using string pointers (not necessarily Memory Manager pointers)
  1442. to the replacement strings.  Using Str255 would copy the string to the
  1443. stack, and then to the text handle.  This way it is only copied once.
  1444. */
  1445.  
  1446. #pragma segment Main
  1447. void MyParamText(StringHandle text, StringPtr cite0, StringPtr cite1)
  1448. {
  1449.     long    offSet;
  1450.     char    param0[2] = {'^', '0'};
  1451.     char    param1[2] = {'^', '1'};
  1452.     long    newLength;
  1453.  
  1454.     if (StrLength(cite0) > 0)
  1455.         offSet = Munger((Handle)text, 1, param0, sizeof(param0), (Ptr)&(cite0[1]), StrLength(cite0));
  1456.     if (StrLength(cite1) > 0)
  1457.         offSet = Munger((Handle)text, 1, param1, sizeof(param1), (Ptr)&(cite1[1]), StrLength(cite1));
  1458.     newLength = GetHandleSize((Handle)text) - 1;
  1459.     if (newLength > 255)
  1460.         newLength = 255;
  1461.     (*text)[0] = newLength;                        // string’s new length byte
  1462. }
  1463.  
  1464. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1465. /*
  1466. Given a window’s portRect, this routine will center the rectangle on the
  1467. main device within the desktop region.  This excludes the menu bar area.
  1468. It follows the Apple Human Interface Guidelines for where to place a
  1469. window centered on the screen. That is, 1/3th of the desktop shows above
  1470. the window and 2/3ths below it.  It returns a new rectangle set to the
  1471. centered position.  The top and left of this rectangle can be used with
  1472. MoveWindow.  This routine only considers the main device.  CenterWindowRect
  1473. could take a GDevice as a parameter to center the VAR rect with.  This
  1474. would also allow Alerts or dialogs that are closely associated with a
  1475. document window to be centered relative to the monitor that contains that
  1476. document.  This is also one of the Human Interface Guidelines.  MacApp 2.0
  1477. has a utility CalcScreenRect that you can borrow from to include this.
  1478.  
  1479. WARNING: This routine may move or purge memory.
  1480. */
  1481.  
  1482. #pragma segment Open
  1483. void CenterWindowRect(short variant, Rect *theRect)
  1484. {
  1485.     Point rectSize;
  1486.     short wTitleHeight;
  1487.  
  1488.     wTitleHeight = GetWTitleHeight(variant);        //get title height
  1489.     SetPt(&rectSize, theRect->right, theRect->bottom + wTitleHeight);    //get size of rect
  1490.     SubPt(TopLeft(*theRect), &rectSize);            // include it in size
  1491.  
  1492.     theRect->top = ((qd.screenBits.bounds.bottom - qd.screenBits.bounds.top - GetMBarHeight() - rectSize.v)
  1493.                         / 3) + GetMBarHeight();        //1/3th below menubar, centered horz
  1494.     theRect->left = ((qd.screenBits.bounds.right - qd.screenBits.bounds.left) - rectSize.h) / 2;
  1495.  
  1496.     SetPt(&BottomRight(*theRect), theRect->left, theRect->top);    //return adjusted rect
  1497.     AddPt(rectSize, &BottomRight(*theRect));
  1498.     theRect->top += wTitleHeight;                    //remove title height from rect
  1499. }
  1500.  
  1501. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1502. /*
  1503. Given a window ID, this routine will center the window’s rectangle before
  1504. showing it on the main screen.  This follows the Apple Human Interface
  1505. Guidelines for where to place a centered window on the screen.  If the
  1506. window is closely associated with another window, considerations should be
  1507. given to where that other window is located.  If this other window is on a
  1508. screen other then the main monitor, then it would be best to center the
  1509. window on that other monitor.
  1510.  
  1511. VERSION 1.1: There is a problem with GetNewWindow in the old Mac Plus and
  1512. SE ROMS.  It will call ReleaseResource on the 'WIND' resource within
  1513. GetNewWindow.  This make the handle invalid after the call.  Therefore,
  1514. before calling HPurge, we get the resource once again.
  1515. */
  1516.  
  1517. #pragma segment Open
  1518. WindowPtr GetCenteredWindow(short id, Ptr p, WindowPtr behind)
  1519. {
  1520.     Rect newRect;
  1521.     WindowTHndl windTemplate;
  1522.     WindowPtr window;
  1523.  
  1524.     window = nil;                                                //initialize result
  1525.     windTemplate = (WindowTHndl)(Get1Resource('WIND', id));
  1526.     if (windTemplate != nil) {
  1527.         HNoPurge((Handle)windTemplate);
  1528.         newRect = (**windTemplate).boundsRect;
  1529.         CenterWindowRect((**windTemplate).procID, &newRect);
  1530.         (**windTemplate).boundsRect = newRect;
  1531.         window = GetNewWindow(id, p, behind);
  1532.         HPurge(Get1Resource('WIND', id));
  1533.     }
  1534.     return(window);
  1535. }
  1536.  
  1537. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1538. /*
  1539. Given an Alert ID, this routine will center the alert’s rectangle before
  1540. showing it on the main screen.  This follows the Apple Human Interface
  1541. Guidelines for where to place a centered window on the screen.  If the
  1542. Alert is closely associated with another window, considerations should be
  1543. given to what the window is located.  If this other window is on a screen
  1544. other then the main monitor, then it would be best to center the Alert on
  1545. that other monitor.
  1546.  
  1547. VERSION 1.2: System 7 supports auto-positioning of windows and dialog, so
  1548. this routine isn't being called anymore. I has been left in the sources
  1549. for the readers that may be interested in knowing how it works.
  1550. */
  1551.  
  1552. #pragma segment Open
  1553. short CenteredAlert(short alertID)
  1554. {
  1555.     AlertTHndl alertHandle;
  1556.     Rect alertRect;
  1557.  
  1558.     alertHandle = (AlertTHndl)(Get1Resource('ALRT', alertID));
  1559.     if (alertHandle != nil) {
  1560.         HNoPurge((Handle)alertHandle);
  1561.         alertRect = (**alertHandle).boundsRect;
  1562.         CenterWindowRect(dBoxProc, &alertRect);
  1563.         (**alertHandle).boundsRect = alertRect;
  1564.         HPurge((Handle)alertHandle);
  1565.     }
  1566.     return(Alert(alertID, nil));
  1567. }
  1568.  
  1569. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1570. /*
  1571. Given a dialog ID, this routine will center the dialog’s rectangle before
  1572. showing it on the main screen.  This follows the Apple Human Interface
  1573. Guidelines for where to place a centered window on the screen.  If the
  1574. dialog is closely associated with another window, considerations should be
  1575. given to what the window is located.  If this other window is on a screen
  1576. other then the main monitor, then it would be best to center the dialog on
  1577. that other monitor.
  1578.  
  1579. VERSION 1.1: There is a problem with GetNewDialog in the old Mac Plus and
  1580. SE ROMS.  It will call ReleaseResource on the 'WIND' resource within
  1581. GetNewWindow.  This make the handle invalid after the call.  Therefore,
  1582. before calling HPurge, we get the resource once again.
  1583.  
  1584. VERSION 1.2: System 7 supports auto-positioning of windows and dialog, so
  1585. this routine isn't being called anymore. I has been left in the sources
  1586. for the readers that may be interested in knowing how it works.
  1587. */
  1588.  
  1589. #pragma segment Open
  1590. DialogPtr GetCenteredDialog(short id, Ptr p, WindowPtr behind)
  1591. {
  1592.     Rect newRect;
  1593.     DialogTHndl dlogTemplate;
  1594.     DialogPtr dialog;
  1595.  
  1596.     dialog = nil;                                                //initialize result
  1597.     dlogTemplate = (DialogTHndl)Get1Resource('DLOG', id);
  1598.     if (dlogTemplate != nil) {
  1599.         newRect = (**dlogTemplate).boundsRect;
  1600.         CenterWindowRect((**dlogTemplate).procID, &newRect);
  1601.         (**dlogTemplate).boundsRect = newRect;
  1602.         HNoPurge((Handle)dlogTemplate);
  1603.         dialog = GetNewDialog(id, p, behind);
  1604.         HPurge(Get1Resource('DLOG', id));
  1605.     }
  1606.     return(dialog);
  1607. }
  1608.  
  1609. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1610. /*
  1611. Given any control handle, this will draw an outline around it.  This is
  1612. used for the default button of a window.  The extra nice feature here is
  1613. that I’ll erase the outline for buttons that are inactive.  Seems like
  1614. there should be a Toolbox call for getting a control’s hilite state.
  1615. Since there isn’t, I have to look into the control record myself.  This
  1616. should be called for update and activate events.
  1617.  
  1618. The method for determining the oval diameters for the roundrect is a
  1619. little different than that recommended by Inside Mac.  IM I-407 suggests
  1620. that you use a hardcoded (16,16) for the diameters. However, this only
  1621. looks good for small roundrects. For larger ones, the outline doesn’t
  1622. follow the inner roundrect because the CDEF for simply buttons doesn’t
  1623. use (16,16). Instead, it uses half the height of the button as the
  1624. diameter. By using this formula, too, our outlines look better.
  1625.  
  1626. WARNING: This will set the current port to the control’s window.
  1627. */
  1628.  
  1629. #pragma segment Main
  1630. void DoButtonOutline(ControlHandle button)
  1631. {
  1632.     Rect theRect;
  1633.     PenState curPen;
  1634.     short buttonOval;
  1635.  
  1636.     if (button != nil) {
  1637.         SetPort((**button).contrlOwner);
  1638.         GetPenState(&curPen);
  1639.         PenNormal();
  1640.         theRect = (**button).contrlRect;
  1641.         InsetRect(&theRect, kButtonFrameInset, kButtonFrameInset);
  1642.         buttonOval = (theRect.bottom - theRect.top) / 2;
  1643.         if (((**button).contrlHilite == kControlNoPart))
  1644.             PenPat(&qd.black);
  1645.         else
  1646.             PenPat(&qd.gray);
  1647.         PenSize(kButtonFrameSize, kButtonFrameSize);
  1648.         FrameRoundRect(&theRect, buttonOval, buttonOval);
  1649.         SetPenState(&curPen);
  1650.     }
  1651. }
  1652.  
  1653. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1654. /*
  1655. Given the button control handle, this will cause the button to look as
  1656. if it has been clicked in.  This is nice to do for the user if they type
  1657. return or enter to select the default item.
  1658. */
  1659.  
  1660. #pragma segment Main
  1661. void SelectButton(ControlHandle button)
  1662. {
  1663.     long finalTicks;
  1664.  
  1665.     HiliteControl(button, kHiliteControlSelect);
  1666.     Delay(kDelayTime, &finalTicks);
  1667.     HiliteControl(button, kHiliteControlDeselect);
  1668. }
  1669.  
  1670. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1671. /*
  1672. Given a sound document, this routine goes through the control list looking
  1673. for a control that needs to be activated, or deactivated what ever the
  1674. case maybe.  The Play button is the default button, and it also needs its
  1675. outline drawn.  The Stop button is always active on the front most window.
  1676. This is true even if there is no selection made in the window’s list.  The
  1677. Stop button is a global action, regardless of what is happening in the window.
  1678.  
  1679. VERSION 1.1:  Stop button is only active while a sound is playing.
  1680. */
  1681.  
  1682. #pragma segment Main
  1683. void ActivateSndCntls(SndDocPeek sndDoc)
  1684. {
  1685.     ControlHandle control;
  1686.     long cntlRefCon;
  1687.     Boolean activate;
  1688.  
  1689.     activate = ((WindowPeek)sndDoc)->hilited && HasSelection(sndDoc);
  1690.     control = ((WindowPeek)sndDoc)->controlList;
  1691.     while (control != nil) {
  1692.         cntlRefCon = GetControlReference(control);
  1693.         if (    (cntlRefCon == rPlaySndCntl)
  1694.              || (cntlRefCon == rHyperPlayCntl)
  1695.              || (cntlRefCon == rPlayScaleCntl)
  1696.              || (cntlRefCon == rMelodyCntl)) {
  1697.             if (activate)
  1698.                 HiliteControl(control, kControlNoPart);
  1699.             else
  1700.                 HiliteControl(control, kControlInactivePart);
  1701.             if (cntlRefCon == rPlaySndCntl)
  1702.                 DoButtonOutline(control);
  1703.         }
  1704.         if (cntlRefCon == rStopCntl) {
  1705.             if (((WindowPeek)sndDoc)->hilited && HasChannelOpen())
  1706.                 HiliteControl(control, kControlNoPart);
  1707.             else
  1708.                 HiliteControl(control, kControlInactivePart);
  1709.         } //cntlRefCon == rStopCntl
  1710.         if (cntlRefCon == rRecordCntl) {
  1711.             if (((WindowPeek)sndDoc)->hilited)
  1712.                 HiliteControl(control, kControlNoPart);
  1713.             else
  1714.                 HiliteControl(control, kControlInactivePart);
  1715.         } //cntlRefCon == rRecordCntl
  1716.         control = (**control).nextControl;
  1717.     }
  1718. }
  1719.  
  1720. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1721. /*
  1722. Check if a window belongs to a desk accessory.  This will first test for a
  1723. nil window.  DAs will have a negitive windowKind.
  1724. */
  1725.  
  1726. #pragma segment Main
  1727. Boolean IsDAWindow(WindowPtr window)
  1728. {
  1729.     if (window == nil)
  1730.         return(false);
  1731.     else    //DA windows have negative windowKinds
  1732.         return(((WindowPeek)window)->windowKind < 0);
  1733. }
  1734.  
  1735. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1736. /*
  1737. Check to see if a window is a document window.  This will first test for a
  1738. nil window.  Document windows all have a refCon set to rSoundWindow.  This
  1739. insures there is document type information after the window record.
  1740. */
  1741.  
  1742. #pragma segment Main
  1743. Boolean IsDocWindow(WindowPtr window)
  1744. {
  1745.     Boolean    result;
  1746.  
  1747.     if (window == nil)
  1748.         result = false;
  1749.     else
  1750.         result = (GetWRefCon(window) == rSoundWindow);
  1751.     return(result);
  1752. }
  1753.  
  1754. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1755. /*
  1756. This test will return true for a window that needs to be treated as a
  1757. modal window.  To include additional windows, add the window’s refCon
  1758. value to the set of modal windows.
  1759. */
  1760.  
  1761. #pragma segment Main
  1762. Boolean IsModalWindow(WindowPtr window)
  1763. {
  1764.     long    wRef;
  1765.     Boolean    result;
  1766.  
  1767.     if (window == nil)
  1768.         result = false;
  1769.     else {
  1770.         wRef = GetWRefCon(window);
  1771.         result = (wRef == rAboutWindow);         // test for all our modal windows
  1772.     }
  1773.     return(result);
  1774. }
  1775.  
  1776. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1777. /*
  1778. This is used to free up all the sound data and channels in use.  There are
  1779. two reasons for using this routine.  One is after a sound has completed
  1780. the other is to terminate a sound that may be in progress.  For this
  1781. second reason, this routine should always be used before playing a new
  1782. sound.  When disposing of a sound channel, this sets all document’s
  1783. sndInUse flags to false.  I can call this routine at any time.  When I
  1784. find that the memory reserve is used, I will call this to free up any
  1785. possible sound resources which tend to be large.  Another important point
  1786. is the human interface issue of hiding the status window.  It’s possible
  1787. that  playing some short sounds could cause the status window to disappear
  1788. before the user had much of a chance to see it.  To solve this, there is a
  1789. delay that insures the status window was visible for a minimal time.
  1790.  
  1791. VERSION 1.1:  Update the document's controls since know that the sound
  1792. is no longer playing the buttons in the document window need to be updated.
  1793. */
  1794.  
  1795. #pragma segment Main
  1796. void KillSound(void)
  1797. {
  1798.     WindowPtr window;
  1799.  
  1800.     if (HasChannelOpen()) {                            // if a channel is open...
  1801.         window = FrontWindow();                        // set all document’s flags
  1802.         while (window != nil) {
  1803.             if (IsDocWindow(window))                // if this is my document...
  1804.                 ((SndDocPeek)window)->sndInUse = false; // then it is no longer active
  1805.             window = (WindowPtr)((WindowPeek)window)->nextWindow;
  1806.         }
  1807.     }
  1808.     if (HasSoundCompleted()) {                        // why were we called?
  1809.         DoSoundComplete();                            // from completion
  1810.  
  1811.         // delay for status window to show a minimal amount of time
  1812.         while ((TickCount() - gStatusWindow->showTime) < kShowTimeDelay) {};
  1813.     }
  1814.     else
  1815.         FreeAllChans();                                // or just because
  1816.     HideWindow((WindowPtr)gStatusWindow);
  1817.     window = FrontWindow();
  1818.     if (IsDocWindow(window))
  1819.         ActivateSndCntls((SndDocPeek)window);
  1820. }
  1821.  
  1822. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1823. /*
  1824. Close any of my windows.  At this point, if there was a document
  1825. associated with a window, you could do any document saving processing if
  1826. it has been changed since being opened.  DoCloseWindow would return true
  1827. if the window actually closed.  false would be returned, as an example, if
  1828. the user chose “Cancel” in the Save As… dialog.  An important detail is if
  1829. the window to be close is one of my documents that is currently playing a
  1830. sound.  We cannot dispose of it yet, since the sound resource owned by the
  1831. document would be in use by the Sound Manager.  So, I test the document’s
  1832. sndInUse flag and if it is in use I call KillSound.  The About window
  1833. contains some resource handles.  I only mark them purgeable, but I could
  1834. use ReleaseResource and then DisposHandle.
  1835. */
  1836.  
  1837. #pragma segment Main
  1838. Boolean DoCloseWindow(WindowPtr window)
  1839. {
  1840.     Boolean        result = true;
  1841.  
  1842.     switch (GetWRefCon(window)) {
  1843.  
  1844.         case rSoundWindow:
  1845.             if (((SndDocPeek)window)->sndInUse)        // contain a snd in use?
  1846.                 KillSound();                        // not any more
  1847.             if (((SndDocPeek)window)->list != nil)    // dispose of document data
  1848.                 LDispose(((SndDocPeek)window)->list);
  1849.             if (((SndDocPeek)window)->resFile != 0)
  1850.                 CloseResFile(((SndDocPeek)window)->resFile);
  1851.             CloseWindow((WindowPtr)window);
  1852.             DisposePtr((Ptr)window);                // dispose of our doc storage
  1853.             break;
  1854.  
  1855.         case rStatusWindow:
  1856.             DisposeHandle((Handle)gStatusWindow->message);
  1857.             CloseWindow((WindowPtr)gStatusWindow);
  1858.             DisposePtr((Ptr)gStatusWindow);
  1859.             break;
  1860.  
  1861.         case rAboutWindow:
  1862.             if (((AboutWPeek)window)->comment != nil)    // never dispose...
  1863.                 HPurge(((AboutWPeek)window)->comment);    // a Resource handle
  1864.             if (((AboutWPeek)window)->appPict != nil)
  1865.                 HPurge(((AboutWPeek)window)->appPict);
  1866.             CloseWindow((WindowPtr)window);
  1867.             DisposePtr((Ptr)window);
  1868.             break;
  1869.  
  1870.         default:
  1871.             if (IsDAWindow(window))                        // we can close DAs too
  1872.                 CloseDeskAcc(((WindowPeek)window)->windowKind);
  1873.             break;
  1874.  
  1875.     } // switch GetWRefCon(window)
  1876.     return(result);
  1877. }
  1878.  
  1879. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1880. /*
  1881. Display an alert to inform the user of an error.  MessageID acts as an
  1882. index into a STR# resource of error messages.  This will attempt to
  1883. replace the error number with a string if the sound is a Sound Manager
  1884. error.
  1885.  
  1886. BUG NOTE: GetIndString will return a bogus string if the index is not
  1887. positive.
  1888. */
  1889.  
  1890. #pragma segment Main
  1891. void AlertUser(short error, short messageID)
  1892. {
  1893.     Str255    msg1;
  1894.     Str255    msg2;
  1895.     short    theItem;
  1896.  
  1897.     UseResFile(gAppResRef);                        // restore our resource file
  1898.     if (messageID > 0)
  1899.         GetIndString(msg1, sErrStrings, messageID);
  1900.     else
  1901.         msg1[0] = 0;                            // case there’s no message
  1902.     if ((error <= noHardware) && (error >= badFormat))
  1903.         GetIndString(msg2, sSMErrStrings, AbsoluteValue(error) + noHardware + 1);
  1904.     else
  1905.         NumToString(error, msg2);
  1906.     ParamText(msg1, msg2, "\p", "\p");
  1907.     theItem = Alert(rUserAlert, nil);
  1908. }
  1909.  
  1910. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1911. /*
  1912. Display an alert that tells the user an error occurred, then exit the
  1913. program.  This routine is used as an ultimate bail-out for serious errors
  1914. that prohibit the continuation of the application.  Errors that do not
  1915. require the termination of the application are handled with AlertUser.
  1916. Error checking and reporting has a place even in the simplest application.
  1917.  
  1918. BUG NOTE: GetIndString will return a bogus string if the index is not
  1919. positive.
  1920. */
  1921.  
  1922. #pragma segment Main
  1923. void EmergencyExit(short message)
  1924. {
  1925.     Str255    msg;
  1926.     short    theItem;
  1927.  
  1928.     SetCursor(&qd.arrow);
  1929.     if (message > 0)
  1930.         GetIndString(msg, sErrStrings, message);
  1931.     else
  1932.         msg[0] = 0;                                // case there’s no message
  1933.     ParamText(msg, "\p", "\p", "\p");
  1934.     theItem = Alert(rExitAlert, nil);
  1935.     ExitToShell();                                //gotta go!
  1936. }
  1937.  
  1938. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1939. /*
  1940. Clean up the application and exit.  I close all of the windows so that
  1941. they can update their documents, if any.  Dispose of the SoundUnit and
  1942. close the status window if the user really wants to quit.
  1943. */
  1944.  
  1945. #pragma segment Main
  1946. void Terminate(void)
  1947. {
  1948.     WindowPtr aWindow;
  1949.     Boolean closed;
  1950.  
  1951.     closed = true;
  1952.     KillSound();                                    //stop any sound in progress
  1953.     do {
  1954.         aWindow = FrontWindow();                    //get the current front window
  1955.         if (aWindow != nil)
  1956.             closed = DoCloseWindow(aWindow);        //close this window
  1957.     } while ((closed) && (aWindow != nil));            //do all windows
  1958.     if (closed) {
  1959.         FreeSoundUnit();                            //get rid of all sound equipment
  1960.         gTerminate = true;                            //exit if no cancellation
  1961.     }
  1962. }
  1963.  
  1964. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1965. /*
  1966. Draw the status message and update the button.  I setup a rectangle that
  1967. is the text area.  This is the entire window area, inset a small amount.
  1968. I also subtract from the bottom of the rectangle the area used by the button.
  1969. Doing things this way allowed me to change the size of the window and
  1970. not change any of this code.  The rectangle used by text will fill the
  1971. window regardless of the new size I give it in the WIND resource.
  1972. */
  1973.  
  1974. #pragma segment Main
  1975. void DrawStatusWindow(void)
  1976. {
  1977.     Rect    theRect;
  1978.  
  1979.     PenNormal();
  1980.     theRect = ((WindowPtr)gStatusWindow)->portRect;
  1981.     theRect.bottom = theRect.bottom - kDafaultButSizeH;
  1982.     InsetRect(&theRect, kStadardWhiteSpacing, kStadardWhiteSpacing);
  1983.     HLock((Handle)gStatusWindow->message);
  1984.     TETextBox((*(gStatusWindow->message) + 1),
  1985.                 **(gStatusWindow->message), &theRect, teJustLeft);
  1986.     HUnlock(((Handle)gStatusWindow->message));
  1987.     UpdateControls((WindowPtr)gStatusWindow, ((WindowPtr)gStatusWindow)->visRgn);
  1988.     DoButtonOutline(((WindowPeek)gStatusWindow)->controlList);
  1989. }
  1990.  
  1991. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1992. /*
  1993. Whenever I start a sound, I show this status window.  It will contain a
  1994. message showing what is currently happening.  A very good rule is not to
  1995. perform drawing outside of the update event.  I bend that rule here.  I
  1996. could simply select this window and show it.  This would allow my normal
  1997. drawing and activating routines to be called.  The problem with that was,
  1998. I found that many times the status window appeared and then disappeared
  1999. before these update routines had a chance to draw the window.  This left
  2000. the user with a blank window that immediately went away.  So, I do the
  2001. activation and drawing right after showing it.
  2002.  
  2003. BUG NOTE: GetIndString will return a bogus string if the index is not
  2004. positive.
  2005. */
  2006.  
  2007. #pragma segment Main
  2008. void ShowStatusWindow(short messageID)
  2009. {
  2010.     Str255    msg;
  2011.  
  2012.     if (FailLowMemory(0)) {                            // running low on memory?
  2013.         KillSound();
  2014.         AlertUser(memFullErr, sLowMemory);
  2015.     }
  2016.     else {
  2017.         if (messageID > 0)
  2018.             GetIndString(msg, sMsgStrings, messageID);
  2019.         else
  2020.             msg[0] = 0;                                    // case there’s no message
  2021.         SetString(gStatusWindow->message, msg);
  2022.         ShowWindow((WindowPtr)gStatusWindow);            // show the window
  2023.         SelectWindow((WindowPtr)gStatusWindow);            // bring it to the front
  2024.         SetPort((WindowPtr)gStatusWindow);
  2025.         EraseRect(&(((WindowPtr)gStatusWindow)->portRect)); // erase old message
  2026.         HiliteControl(((WindowPeek)gStatusWindow)->controlList, kControlNoPart);
  2027.         DrawStatusWindow();                                // draw the new message
  2028.         ValidRect(&(((WindowPtr)gStatusWindow)->portRect)); // avoid needless update
  2029.         gStatusWindow->showTime = TickCount();            // it’s show time folks
  2030.     }
  2031. }
  2032.  
  2033. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2034. /*
  2035. This initializes the status window, and keeps it hidden until the user
  2036. decides to play a sound.  I also center it for the first time, but the
  2037. user is free to drag it to a new location afterwards.  The status window
  2038. also has a message associated to it, so I allocate a string handle for this.
  2039. */
  2040.  
  2041. #pragma segment Initialize
  2042. void InitStatusWindow(void)
  2043. {
  2044.     WindowPtr        window;
  2045.     ControlHandle    stopButton;
  2046.  
  2047.     gStatusWindow = (StatWindowPeek)NewPtrClear(sizeof(StatusWindow));
  2048.     if (gStatusWindow == nil)
  2049.         EmergencyExit(sInitStatusErr);
  2050.     window = GetNewWindow(rStatusWindow, (Ptr)gStatusWindow, (WindowPtr)-1);
  2051.     if (window == nil)
  2052.         EmergencyExit(sInitStatusErr);
  2053.     SetWRefCon(window, rStatusWindow);
  2054.     stopButton = GetNewControl(rCancelCntl, window);
  2055.     if (stopButton == nil)
  2056.         EmergencyExit(sInitStatusErr);
  2057.     gStatusWindow->message = NewString("\p");    // a new empty string handle
  2058.     if (gStatusWindow->message == nil)
  2059.         EmergencyExit(sInitStatusErr);
  2060.     HNoPurge((Handle)gStatusWindow->message);
  2061. }
  2062.  
  2063. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2064. /*
  2065. I just flash the menubar for a moment instead of playing any sounds.  It’s
  2066. the same effect as setting the sound volume to zero but that would prevent
  2067. me playing my sounds.  Also, it helps to prevent the problem of _SysBeep
  2068. being called by the Dialog Manager while I’m playing a sound.  If my
  2069. application is playing a sound and, for example, the user clicks outside
  2070. of the Standard File dialog ModalDialog calls _SysBeep.  This can cause
  2071. the Mac to crash or trash my channel.
  2072.  
  2073. BUG NOTE: If the current Sound Manager were playing a sound and a
  2074. _SysBeep were to occur, bad things could happen on a Mac Plus/SE.  Either
  2075. the application’s channel would be trashed or the Mac could crash.
  2076.  
  2077. VERSION 1.1: The new Sound Manager will handle the problem presented in the
  2078. older Sound Manager regarding SysBeep.  If I'm running under the new Sound
  2079. Manager then I'll call SysBeep anyway.  The new Sound Manager will properly
  2080. handle the situation of an open sound channel when SysBeep is called.
  2081.  
  2082. VERSION 1.2: This is no longer needed since we only use Sound Manager 2 or later.
  2083. */
  2084.  
  2085. #pragma segment Main
  2086. pascal void DoErrorSound(short soundNo)
  2087. {
  2088.     long finalTicks;
  2089.  
  2090.     if (GetSoundMgrVersion() == 1) {
  2091.         if (soundNo > 0) {                        //only after the first time
  2092.             FlashMenuBar(0);
  2093.             Delay(kDelayTime, &finalTicks);
  2094.             FlashMenuBar(0);
  2095.         }
  2096.     }
  2097.     else
  2098.         SysBeep(30);                            //does the right thing now
  2099. }
  2100.  
  2101. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2102. /*
  2103. This tests if the volume has been set very low.  It’s a judgement call as
  2104. to what “too low” means.  The user sets the volume, so how could it be too
  2105. low? A setting of 0 could be considered too low, but in any case do not
  2106. adjust it.  I find the volume goes below 4 on a standard Mac, then there
  2107. is a perceivable difference.  I also wanted to show this routine as a
  2108. demonstration in how to handle such a situation.  Do not change it
  2109. directly! Ask the user to do it.  Consider the user that has their Mac
  2110. connected to a stack of Marshalls (which go to 11) and has purposely set
  2111. their Mac’s volume where they wanted it.  This may be 3 and if you crack
  2112. it up to 8, it could be a scene out of Back to the Future.
  2113.  
  2114. User Interface rule, let the user remain in control!
  2115.  
  2116. VERSION 1.2: Don't use GetSoundVol anymore. This just reads a low memory global
  2117. which is no longer valid with Sound Manager 3 or later. The old low global
  2118. is only 3 bits, which is why the range used to be 0-7. There are new machines
  2119. supported by Sound Manager 3 that have more than 8 volume level. So the
  2120. old global is scaled into the 0-7 range. You should avoid all of this non-sense
  2121. and start using the new calls of Sound Manager 3, and start using percentages.
  2122. */
  2123.  
  2124. #pragma segment Initialize
  2125. void CheckSoundVolume(void)
  2126. {
  2127.     Fixed    percent;
  2128.     long    soundVolume;
  2129.     short    curVolume;
  2130.     short    item;
  2131.     Str255    numStr;
  2132.  
  2133.     if (GetSoundMgrVersion() < 3)
  2134.     {
  2135.         // turn old 0-7 range into the new 0-0x0100 range
  2136.  
  2137.         curVolume = LMGetSdVolume();                // same as calling GetSoundVol()
  2138.         curVolume *= kFullVolume;
  2139.         curVolume += 7-1;                            // avoid rounding errors
  2140.         curVolume /= 7;                                // divid by old max
  2141.     }
  2142.     else
  2143.     {
  2144.         // get the current stereo levels and average them
  2145.  
  2146.         GetDefaultOutputVolume(&soundVolume);
  2147.         curVolume = (soundVolume >> 16) + (soundVolume & 0x0000FFFF);
  2148.         curVolume /= 2;
  2149.     }
  2150.  
  2151.     // take the current level and turn this in to a percentage of full volume,
  2152.     // then show the user that the level is low and how they may increase it.
  2153.  
  2154.     percent = FixDiv( (long)curVolume << 16, kFullVolume << 16);
  2155.     percent = FixMul(percent, 100L << 16);
  2156.     NumToString(percent >> 16, numStr);
  2157.     ParamText(numStr, "\p", "\p", "\p");        // show the current volume
  2158.     item = Alert(rSoundVolAlert, nil);
  2159. }
  2160.  
  2161. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2162. /*
  2163. Simply add all the buttons I want to use in the document window.  I get
  2164. the control templates, and add the control to the window.  I don’t check
  2165. for getting errors for two reasons.  I put these controls there.  If the
  2166. user removes them, it’s their problem.  If the application cannot get the
  2167. memory required for these, then the application is already out of memory
  2168. and checking here probably wouldn’t help much.  I do check before creating
  2169. the document that there was enough available memory.  I save the resource
  2170. ID into the control’s refCon so later I can tell which control was hit by
  2171. the user.
  2172.  
  2173. VERSION 1.1: Add the record button to the window.}
  2174. */
  2175.  
  2176. #pragma segment Open
  2177. void AddSndDocControls(WindowPtr window)
  2178. {
  2179.     ControlHandle    control;
  2180.  
  2181.     control = GetNewControl(rPlaySndCntl, window);
  2182.     if (control != nil)
  2183.         SetControlReference(control, rPlaySndCntl);
  2184.  
  2185.     control = GetNewControl(rHyperPlayCntl, window);
  2186.     if (control != nil)
  2187.         SetControlReference(control, rHyperPlayCntl);
  2188.  
  2189.     control = GetNewControl(rPlayScaleCntl, window);
  2190.     if (control != nil)
  2191.         SetControlReference(control, rPlayScaleCntl);
  2192.  
  2193.     control = GetNewControl(rMelodyCntl, window);
  2194.     if (control != nil)
  2195.         SetControlReference(control, rMelodyCntl);
  2196.  
  2197.     control = GetNewControl(rStopCntl, window);
  2198.     if (control != nil)
  2199.         SetControlReference(control, rStopCntl);
  2200.  
  2201.     control = GetNewControl(rRecordCntl, window);
  2202.     if (control != nil)
  2203.         SetControlReference(control, rRecordCntl);
  2204. }
  2205.  
  2206. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2207. #pragma segment Open
  2208. Boolean PositionAvailable(Point newPt, short wTitleHeight)
  2209. {
  2210.     WindowPtr oldWindow;
  2211.     Point delta;
  2212.     Point oldPt;
  2213.     Boolean taken;
  2214.  
  2215.     taken = false;
  2216.     oldWindow = FrontWindow();
  2217.     while ((oldWindow != nil) && !taken) {
  2218.         if (IsDocWindow(oldWindow) && ((WindowPeek)oldWindow)->visible) {
  2219.             oldPt = GetGlobalTopLeft(oldWindow);
  2220.             delta.v = AbsoluteValue(newPt.v - oldPt.v);
  2221.             delta.h = AbsoluteValue(newPt.h - oldPt.h);
  2222.             taken = (delta.h + delta.v)
  2223.                         <= ((kWindowPosStaggerH + kWindowPosStaggerV + wTitleHeight) / 2);
  2224.         }
  2225.         oldWindow = (WindowPtr)(((WindowPeek)oldWindow)->nextWindow);
  2226.     }
  2227.     return(!taken);
  2228. }
  2229.  
  2230. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2231. /*
  2232. There are a few approaches I thought of and tried, none of which satisfied
  2233. me.  ResEdit uses the simplest method, an offset from the front window.  I
  2234. don’t like this because it may cover up existing windows.  So my approach is
  2235. to go through the window list looking for an empty spot.  If the empty
  2236. spot causes the window to go off the screen, then I start a new stack off
  2237. to the right.  This will cause a new series of window to be stacked.  If the
  2238. new stack would cause the window to go off screen, then it’s time to give up.
  2239. All new windows will then be moved to the starting point and there is no
  2240. further stacking.  If I look at this routine too much, I get real tired.
  2241. If I try to change it at all, I get woozy trying to make it work again.
  2242.  
  2243. VERSION 1.2: System 7 provides for staggering windows, but it doesn't work
  2244. exactly the way I want it. Mine's better.
  2245. */
  2246.  
  2247. #pragma segment Open
  2248. WindowPtr NewStackedWindow(short windID, Ptr windStorage)
  2249. {
  2250.     Point windSize;
  2251.     Point newPt;
  2252.     WindowPtr newWindow;
  2253.     short wTitleHeight;
  2254.     short numStacks;
  2255.     Boolean taken;
  2256.  
  2257.     //set the initail starting point for a window, less the staggering amount
  2258.     newWindow = GetNewWindow(windID, windStorage, (WindowPtr)-1);
  2259.     windSize = BottomRight(newWindow->portRect);
  2260.     SubPt(TopLeft(newWindow->portRect), &windSize);
  2261.     wTitleHeight = GetWTitleHeight(GetWVariant(newWindow));
  2262.     SetPt(&newPt, kWindowPosStartPt - kWindowPosStaggerH, kWindowPosStartPt - kWindowPosStaggerV + GetMBarHeight());
  2263.  
  2264.     numStacks = 0;
  2265.     do { //add the staggering amount then test if the window goes off the screen
  2266.         taken = true;
  2267.         SetPt(&newPt, newPt.h + kWindowPosStaggerH, newPt.v + kWindowPosStaggerV + wTitleHeight);
  2268.         if (    ((newPt.v + windSize.v) > qd.screenBits.bounds.bottom)
  2269.              || ((newPt.h + windSize.h) > qd.screenBits.bounds.right))
  2270.         {
  2271.             numStacks++;
  2272.             SetPt(&newPt, kWindowPosStartPt + (numStacks * kWindowPosStaggerH),
  2273.                             kWindowPosStartPt + wTitleHeight + GetMBarHeight());
  2274.             if (((newPt.v + windSize.v) > qd.screenBits.bounds.bottom)
  2275.                         || ((newPt.h + windSize.h) > qd.screenBits.bounds.right)) {
  2276.                 SetPt(&newPt, kWindowPosStartPt, kWindowPosStartPt + wTitleHeight + GetMBarHeight());
  2277.                 taken = false;
  2278.             }
  2279.         }
  2280.     } while (taken && !(PositionAvailable(newPt, wTitleHeight)));
  2281.  
  2282.     MoveWindow(newWindow, newPt.h, newPt.v, true);
  2283.     return(newWindow);
  2284. }
  2285.  
  2286. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2287. /*
  2288. Create a new sound document and initialize all the data associated with
  2289. it.  If I encounter an error, then dispose of any memory allocated in the
  2290. attempt.  Allocate all necessary memory required for a sound document.  I
  2291. like to use NewPtrClear because is will initialize all the memory.  I
  2292. depend on real values or zero in my document fields.  Then its time to
  2293. build a sound document which contains all the controls and the list of
  2294. sounds.  I get the position for the list kept in a rectangle resource.
  2295. This  helps me to adjust the size of the list without changing code.  I
  2296. will make  an additional adjustment to the list’s height to insure better
  2297. scrolling.  This avoids the ugly white space of an improperly sized
  2298. rectangle.  If I cannot create the list, I’ll close the window and return
  2299. a NIL.  If I find after creating a new document that I’m low on memory,
  2300. I’ll close it and return an error.
  2301.  
  2302. SPECIAL NOTE: The Human Interface Group suggested that the buttons and the
  2303. list should in the System font.  I designed these windows using the
  2304. application font in 10 point.  If you change the call to TextFont, you
  2305. find that the buttons and the list will work properly in your font choice.
  2306.  
  2307. VERSION 1.1:  Size the window smaller to hide the record button from the
  2308. user if Sound Input is not available.  Added memory check to the beginning
  2309. of this routine before creating the document.  This was done because there
  2310. are two routines that call this one, OpenSoundDoc and NewSoundDoc which
  2311. both performed this check.  Having it here in one place reduces the chance of
  2312. future bugs (doing the same thing in two places) and reduces the size of
  2313. the code.
  2314. */
  2315.  
  2316. #pragma segment Open
  2317. OSErr CreateSoundDoc(short resRef, FSSpecPtr file)
  2318. {
  2319.     SndDocPeek newDocPtr;
  2320.     WindowPtr window;
  2321.     ListHandle list;
  2322.     RectHandle rHandle;
  2323.     Rect lView;
  2324.     Rect lBounds;
  2325.     Cell aCell;
  2326.     Point cSize;
  2327.     Point newSize;
  2328.     short maxListHeight;
  2329.     OSErr theErr;
  2330.     Boolean ignore;
  2331.  
  2332.     if (FailLowMemory(kMemForSndDoc)) {
  2333.         CloseResFile(resRef);                            //close it before leaving
  2334.         return(memFullErr);
  2335.     }
  2336.  
  2337.     theErr = noErr;
  2338.     newDocPtr = (SndDocPeek)NewPtrClear(sizeof(SndDocument));
  2339.     if (newDocPtr != nil) {
  2340.         window = NewStackedWindow(rSoundWindow, (Ptr)newDocPtr);
  2341.         SetPort(window);
  2342.         if (! HasSoundInput())
  2343.             SizeWindow(window, kSoundWindowSizeW,
  2344.                     kSoundWindowSizeH - (kStadardWhiteSpacing + kSndButtonSizeH), false);
  2345.         TextFont(0);                                    //set window to System font, blech
  2346.         AddSndDocControls(window);                        //add my buttons
  2347.         SetWRefCon((WindowPtr)newDocPtr, rSoundWindow); //mark as an app window
  2348.         SetWTitle((WindowPtr)newDocPtr, file->name);
  2349.         newDocPtr->resFile = resRef;                    //save its resource file ref
  2350.         newDocPtr->vRefNum = file->vRefNum;                //save its volume reference
  2351.         newDocPtr->dirID = file->parID;                    //save its directory ID
  2352.         newDocPtr->sndInUse = false;                    //not yet it doesn’t
  2353.         rHandle = (RectHandle)Get1Resource('RECT', rListRectID);
  2354.         if (rHandle != nil) {                            //get the stored list size
  2355.             lView = **rHandle;
  2356.             SetRect(&lBounds, 0, 0, 1, 0);                //one dimentional list
  2357.             SetPt(&cSize, 0, 0);                        //List Mgr will find cell size
  2358.             list = LNew(&lView, &lBounds, cSize, 0, window, false, false, false, true);
  2359.             maxListHeight = window->portRect.bottom - window->portRect.top - (2 * kStadardWhiteSpacing);
  2360.             if (maxListHeight < (lView.bottom - lView.top))
  2361.                 maxListHeight = (lView.bottom - lView.top);
  2362.             if (list != nil) {
  2363.                 newSize.h = (**list).cellSize.h;        //get the width of one cell
  2364.                 newSize.v = maxListHeight;                //get the best height for all cells
  2365.                 newSize.v -= maxListHeight % (**list).cellSize.v;
  2366.                 LSize(newSize.h, newSize.v, list);        //adjust for best scrolling
  2367.                 (**list).selFlags = lOnlyOne;            //single selections only
  2368.                 newDocPtr->list = list;                    //save the list handle
  2369.                 theErr = InitSndList(newDocPtr);        //initialize the list data
  2370.                 if (theErr == noErr) {
  2371.                     SetPt(&aCell, 0, 0);                //by default, I will...
  2372.                     LSetSelect(true, aCell, newDocPtr->list); //select first item
  2373.                     LSetDrawingMode(true, newDocPtr->list);
  2374.                     ShowWindow((WindowPtr)newDocPtr);    //get the show on the road
  2375.                     if (FailLowMemory(0))                //if I’m low on memory...
  2376.                         theErr = memFullErr;
  2377.                 }
  2378.             }
  2379.             else
  2380.                 theErr = nilHandleErr;                    //list handle was NIL
  2381.         }
  2382.         else
  2383.             theErr = nilHandleErr;                        //RECT handle was NIL
  2384.         if (theErr != noErr) {                            //could not create the list
  2385.             ignore = DoCloseWindow(window);                //if not, close the window
  2386.             newDocPtr = nil;                            //return nil pointer too
  2387.         }
  2388.     }
  2389.     else                                                //NewPtrClear was nil
  2390.         theErr = MemError();
  2391.     return(theErr);                                        //return the error, if any
  2392. }
  2393.  
  2394. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2395. /*
  2396. Believe it or not, but this turned out to be one of the more difficult
  2397. routines to write.  This was the best approach I could thing of to avoid
  2398. serious problems.  I don’t center the Standard File dialog because it
  2399. wouldn’t be under the File menu where the user probably has the mouse.  I
  2400. use OpenRFPerm because it allows for permissions and doesn’t depend on the
  2401. current directory.  First problem with opening a resource file was to
  2402. check if the file already being open.  Read Tech Notes #116 and #185.
  2403. GetFInfo seems to do the trick.  At least it does report all files that
  2404. are open on this machine.  It may be incorrect for files on AppleShare
  2405. opened by other machines.  What I’m worried about is when opening a
  2406. resource file for the second time on the same machine may return the
  2407. previous opener’s resource map.  This is very dangerous, and if the second
  2408. opener calls CloseResFile there will be a crash.  I want to be friendly
  2409. and if the user tries to open the file the second time and I’ve already
  2410. got it on the screen, then I’ll bring that window forward.  To test for
  2411. this, I compare the file’s name, DirID and vRefNum.  The vRefNum is
  2412. dynamic and needs to be converted into a volume name if I were to save
  2413. this information for future use.
  2414.  
  2415. There are a couple pitfalls, even with this method.  The user can open the
  2416. file, then move it to another directory.  This same thing confuses all
  2417. other applications I’ve tested.  Opening a resource file will allocate a
  2418. resource map handle into my heap, which may be large depending on the
  2419. number of resources in that file.  Additionally this loads all resources
  2420. marked “preload.”  So I set ResLoad to false to prevent the preloading.  I
  2421. test if the amount of memory I believe my document will require is
  2422. available after opening the resource file.  If true, I test if there are
  2423. any sound resources in that file and if not alert the user.  After all
  2424. this, create the new document.  If after creating the new document I find
  2425. that memory is too low, will close it and return an error.  If it does
  2426. fail, then close the file before anything else or there may not be enough
  2427. memory to show the alert.  All of these tests created a number of
  2428. IF-THEN-ELSE blocks and became unyielding.  C programmers get a break, so
  2429. gimme me one too.  I use the MPW Pascal EXIT.
  2430.  
  2431. BUG NOTE: Don’t open a resource file that is already open.  OpenResFile
  2432. may return an existing resource map when it gets opWrErr from the file
  2433. system.  If this happens, the resource file will not be unique and this
  2434. is very bad.  Another problem is if I get a read-only path and someone
  2435. else opens it for read/write.  This is also very bad.  Read Tech Notes
  2436. #116 and #185 hint at this problem, but I think a more comprehensive one
  2437. is in order.
  2438.  
  2439. BUG NOTE: GetWDInfo fails with nsvErr if the working directory returned
  2440. from Standard File is the root of an A/UX volume.  I could work around
  2441. this,  but it would be dependant on the current version of A/UX.  Read
  2442. Tech Note #229.  I believe this is also true for TOPS.
  2443.  
  2444. VERSION 1.1:  I'll open files that do not have snd resources in them.
  2445. This allows users to open existing files and then record or paste a sound
  2446. into it.  I changed OpenRFPerm to HOpenResFile to avoid working
  2447. directories and to be consistent with the rest of the sources.  I
  2448. separated the standard file code from OpenSndDoc to support opening
  2449. documents being open from the Finder.  This allows me to share the same
  2450. routine to open files either from double clicking them in the Finder, or
  2451. by the Standard File dialog.  Removed the checking for low memory conditions
  2452. since CreateSoundDoc is now doing this.
  2453. */
  2454.  
  2455. #pragma segment Open
  2456. void OpenSoundDoc(FSSpecPtr file)
  2457. {
  2458.     HParamBlockRec fPBRec;
  2459.     WindowPtr window;
  2460.     short resFileRef;
  2461.     OSErr theErr;
  2462.  
  2463.     fPBRec.fileParam.ioCompletion = nil;            //prepare a paramBlock
  2464.     fPBRec.fileParam.ioNamePtr = file->name;
  2465.     fPBRec.fileParam.ioVRefNum = file->vRefNum;
  2466.     fPBRec.fileParam.ioDirID = file->parID;
  2467.     fPBRec.fileParam.ioFVersNum = 0;
  2468.     fPBRec.fileParam.ioFDirIndex = 0;
  2469.     theErr = PBHGetFInfoSync(&fPBRec);                 //fPBRec on stack, synch only
  2470.     if (theErr == noErr) {
  2471.         if (fPBRec.fileParam.ioFlAttrib & kResForkOpenBit) {
  2472.             if (OpenByApp(file, &window))
  2473.                 SelectWindow(window);                //I opened this one, select it
  2474.             else
  2475.                 AlertUser(noErr, sCurInUseErr);        //in use by someone else
  2476.             return;
  2477.         }
  2478.     } else {
  2479.         AlertUser(theErr, sStandardErr);            //PBGetFInfo failed
  2480.         return;
  2481.     }
  2482.     SetResLoad(false);                                //don’t load any resources
  2483.     resFileRef = FSpOpenResFile(file, fsCurPerm);
  2484.     theErr = ResError();                            //save error, if any
  2485.     SetResLoad(true);                                //restore ResLoad state
  2486.     UseResFile(gAppResRef);                            //changes ResErr
  2487.     if (resFileRef != kResFileNotOpened)            //error from OpenRFPerm?
  2488.         theErr = CreateSoundDoc(resFileRef, file);
  2489.     if (theErr != noErr)
  2490.         AlertUser(theErr, sNewDocErr);                 //couldn’t create new doc
  2491. }
  2492.  
  2493. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2494. /*
  2495. VERSION 1.1:  Create a new file for the user.  I prefer to use the new
  2496. HCreateResFile to avoid working directories, and to be consistent with
  2497. the rest of the sources.  Also, I need the real vRefNum and dirID to
  2498. store in the sndDoc record.  After creating the file, I set its Finder
  2499. information to the proper type and creator.  Finally, I get to open the
  2500. new file.  After this point everything is exactly like opening an
  2501. existing file and creating a new sound document.
  2502.  
  2503. VERSION 1.2: If dupFNErr is returned by HCreateResFile, then the user
  2504. wants to replace the file with a new SoundApp document.
  2505. */
  2506.  
  2507. #pragma segment Open
  2508. void NewSoundDoc(void)
  2509. {
  2510.     Str255 msg;
  2511.     StandardFileReply reply;
  2512.     StringHandle strHandle;
  2513.     short resFileRef;
  2514.     OSErr theErr;
  2515.  
  2516.     strHandle = (StringHandle)Get1Resource('STR ', rPutFileMsg);
  2517.     if (strHandle != nil)
  2518.         PStringCopy(*strHandle, msg);                        //save no name title
  2519.     else
  2520.         msg[0] = 0;                                            //at least an empty string
  2521.  
  2522.     StandardPutFile(msg, "\p", &reply);
  2523.     if (reply.sfGood)
  2524.     {
  2525.         theErr = noErr;
  2526.         if (reply.sfReplacing)
  2527.             theErr = FSpDelete(&reply.sfFile);                //we're replacing it
  2528.         if (theErr == noErr)
  2529.         {
  2530.             FSpCreateResFile(&reply.sfFile, rAppSignature, rSndAppDocType, reply.sfScript);
  2531.             theErr = ResError();
  2532.             if (theErr == noErr) {
  2533.                 resFileRef = FSpOpenResFile(&reply.sfFile, fsCurPerm);
  2534.                 theErr = ResError();                        //save error, if any
  2535.                 UseResFile(gAppResRef);                        //changes ResErr
  2536.                 if (resFileRef != kResFileNotOpened)        //error from HOpenResFile
  2537.                     theErr = CreateSoundDoc(resFileRef, &reply.sfFile);
  2538.             }
  2539.         }
  2540.         if (theErr != noErr)
  2541.             AlertUser(theErr, sNewDocErr);                         //return the error
  2542.     }
  2543. }
  2544.  
  2545. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2546. /*
  2547. This is much more than what a typical file filter might do but I wanted
  2548. the user to easily find files that contained snd resources.  So, the
  2549. global flag gSndFilesOnly is used to determine when to filter for such
  2550. files.  Otherwise, I show all files and allow the application to report to
  2551. the user the file they’ve just tried to open doesn’t have any sounds to
  2552. play with.  Opening resource forks can be tricky if it’s already open.  It
  2553. would be very bad to use a resource fork that is already open by another
  2554. application.  The problem being that the Resource Manager doesn’t deal
  2555. with multiple users.  Read Tech notes #116 and #185.  There’s also another
  2556. problem.  If a resource fork is opened by two applications and one closes
  2557. the file then the entire resource fork may closed out from underneath the
  2558. other application.  I do, however, want to show the user files that
  2559. contain sound resources even if they are currently open.  I use
  2560. HOpenResFile with read only permission, which will give me a unique
  2561. resource reference.  I look for a 'snd ' resource and then immediately
  2562. close the file.  Do not use a resource file opened with read only
  2563. permission.  Another reason to use HOpenResFile  is to avoid a necessary
  2564. working directory.  I do not have one while in the file filter, but can
  2565. use the DirID.  Performing this search on each file is time consuming so I
  2566. show a spinning cursor to show the user I’m working.   Opening a resource
  2567. fork may load resources mark preload.   To avoid this, I call SetResLoad
  2568. to false.  I bet you thought the Resource Manager was a free lunch.  Ha!
  2569. Read Tech Note #203 for other reasons not to play with resources.
  2570.  
  2571. BUG NOTE: While debugging this routine using heap scramble, I found that
  2572. OpenResFile would not open the requested file.  I’m not sure if this is a
  2573. problem with OpenResFile or SFGetFile.
  2574.  
  2575. VERSION 1.1: The bug mentioned above was found.  The problem is that the
  2576. paramBlock happens to be a re-locatable block in the heap.  Passing the
  2577. de-reference ioNamePtr to HOpenResFile was de-referencing this
  2578. re-locatable paramBlock.  Since HOpenResFile moves memory, the namePtr
  2579. would no longer valid and thus HOpenResFile would fail.  Now I copy the
  2580. name out of the paramBlock and use the local variable in HOpenResFile.
  2581. This problem was fixed in System 7, which no longer passes a re-locatable
  2582. block to the file filter.  The new version allows for any resource file
  2583. to be opened.  Because of this new feature, I only show the user files
  2584. that have a resource fork.
  2585.  
  2586. VERSION 1.2: This is a filter for System 7 now, and I don't show invisible files.
  2587. */
  2588.  
  2589. #pragma segment Open
  2590. pascal Boolean SFFilter(CInfoPBPtr p, Boolean *sndFilesOnly)
  2591. {
  2592. #define kShowIt            false                //false means I do not filter out...
  2593. #define kDoNotShowIt    true                //the file and true means that I do.
  2594.  
  2595.     long oldTicks;
  2596.     short resRef;
  2597.     short curRes;
  2598.     Boolean result;
  2599.  
  2600.     oldTicks = TickCount();
  2601.     result = kDoNotShowIt;                    //don’t show anything until I say so
  2602.  
  2603.     if ( (*sndFilesOnly) && !(p->hFileInfo.ioFlFndrInfo.fdFlags & fInvisible) )
  2604.     {
  2605.         curRes = CurResFile();
  2606.         SetResLoad(false);
  2607.         resRef = HOpenResFile(p->hFileInfo.ioVRefNum, p->hFileInfo.ioFlParID,
  2608.                                 p->hFileInfo.ioNamePtr, fsRdPerm);
  2609.         if (resRef != kResFileNotOpened) {
  2610.             UseResFile(resRef);
  2611.             if (Count1Resources(soundListRsrc) > 0)
  2612.                 result = kShowIt;            //hey, we found a sound in here
  2613.             CloseResFile(resRef);
  2614.         }                                    //restore everything
  2615.         SetResLoad(true);
  2616.         UseResFile(curRes);
  2617.     } else
  2618.     {
  2619.         if (   !(p->hFileInfo.ioFlFndrInfo.fdFlags & fInvisible)    // if not invisible
  2620.              && (p->hFileInfo.ioFlRLgLen > 0) )                        // and has resources
  2621.         {
  2622.             result = kShowIt;
  2623.         }
  2624.     }
  2625.     RotateCursor(TickCount() - oldTicks);
  2626.     return(result);
  2627. }
  2628.  
  2629. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2630. #pragma segment Open
  2631. pascal short SFGetHook(short mySFItem, DialogPtr dialog, void *sndFilesOnly)
  2632. {
  2633.     ControlHandle cntl;
  2634.     Rect r;
  2635.     short kind;
  2636.     short result;
  2637.  
  2638.     result = mySFItem;
  2639.     GetDialogItem(dialog, rSndOnlyCheckBox, &kind, (Handle *)&cntl, &r);
  2640.     switch (mySFItem) {
  2641.  
  2642.         case sfHookFirstCall:
  2643.             if (*(Boolean *)sndFilesOnly)
  2644.                 SetControlValue(cntl, kCntlOn);
  2645.             else
  2646.                 SetControlValue(cntl, kCntlOff);
  2647.             break;
  2648.  
  2649.         case rSndOnlyCheckBox:
  2650.             if (GetControlValue(cntl) == kCntlOff) {
  2651.                 SetControlValue(cntl, kCntlOn);
  2652.                 *(Boolean *)sndFilesOnly = true;
  2653.             }
  2654.             else {
  2655.                 SetControlValue(cntl, kCntlOff);
  2656.                 *(Boolean *)sndFilesOnly = false;
  2657.             }
  2658.             result = sfHookRebuildList;
  2659.             break;
  2660.  
  2661.     }
  2662.     return (result);
  2663. }
  2664.  
  2665. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2666. /*
  2667. VERSION 1.1: This routine used to be inside of OpenSoundDoc.  The
  2668. standard file code was removed to here in order to support opening
  2669. documents being open from the Finder.  I've switched to using a constant
  2670. for the topLeft point of the Standard File dialog.  It saves a few bytes
  2671. of code, so what the hell?  I found a cosmetic problem with the cursor
  2672. not being restored back to arrow after returning Standard File if there
  2673. was an error dialog shown immediately.  So, it is immediately set back to
  2674. the arrow.
  2675. */
  2676.  
  2677. #pragma segment Main
  2678. void GetSoundDoc(void)
  2679. {
  2680.     StandardFileReply reply;
  2681.     SFTypeList typeList;                            //not used, just a placeholder
  2682.     Point sfTopLeft;
  2683.     Boolean sndFilesOnly;
  2684.  
  2685.     SpinCursor(0);                                    //get the spinning cursor ready
  2686.     sfTopLeft.v = -1;                                //-1,-1 means to center the dialog
  2687.     sfTopLeft.h = -1;
  2688.     sndFilesOnly = false;
  2689.     CustomGetFile((FileFilterYDUPP)GetRoutineAddress(SFFilter), -1, typeList, &reply, rCustomGetFileDLOG,
  2690.             sfTopLeft, GetRoutineAddress(SFGetHook), nil, nil, nil, &sndFilesOnly);
  2691.     SetCursor(&qd.arrow);
  2692.     if (reply.sfGood)
  2693.         OpenSoundDoc(&reply.sfFile);
  2694. }
  2695.  
  2696. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2697. /*
  2698. Draw the contents of the about window in response to an update event.  At
  2699. this point, BeginUpdate has been called which sets the window’s visRgn to
  2700. clip drawing only where it needs to be done.  I have some text to draw, an
  2701. icon, a picture, and a default button with its outline.  If I have a color
  2702. icon handle I’ll call PlotCIcon.  I offset the picture to draw to the
  2703. right of the icon.  The text will appear in a rectangle as large as the
  2704. window, but below the icon and above the button.  This allows me the
  2705. change the text and if needed change the size of the window’s rectangle to
  2706. compensate.  I won’t have to recompile any code.  Some people use dialogs
  2707. because of this, but I’m demonstrating how it can be done without them.  I
  2708. use UpdateControls to avoid needless drawing that happens with DrawControls.
  2709. It not only runs faster but doesn’t flicker.
  2710.  
  2711. VERSION 1.2: Uses System 7's PlotIcon to draw the proper icon.
  2712. */
  2713.  
  2714. #pragma segment Main
  2715. void DrawAboutWindow(WindowPtr window)
  2716. {
  2717.     Rect theRect;
  2718.     OSErr ignoreErr;
  2719.  
  2720.     PenNormal();
  2721.     SetRect(&theRect, kStdAlertIconLeft, kStdAlertIconTop, kStdAlertIconRight, kStdAlertIconBottom);
  2722.     ignoreErr = PlotIconID(&theRect, atNone, ttNone, rMoofIcon);
  2723.  
  2724.     theRect = (**(PicHandle)((AboutWPeek)window)->appPict).picFrame;
  2725.     OffsetRect(&theRect, -theRect.left + kStdAlertIconRight + kStadardWhiteSpacing,
  2726.                             -theRect.top + kStdAlertIconTop);
  2727.     DrawPicture((PicHandle)((AboutWPeek)window)->appPict, &theRect);
  2728.  
  2729.     SetRect(&theRect, window->portRect.left, kStdAlertIconBottom,
  2730.                 window->portRect.right,
  2731.                 window->portRect.bottom - kDafaultButSizeH);
  2732.     InsetRect(&theRect, kStadardWhiteSpacing, kStadardWhiteSpacing);
  2733.     HLock(((AboutWPeek)window)->comment);
  2734.     TETextBox(*(((AboutWPeek)window)->comment) + 1,
  2735.                 StrLength(*(((AboutWPeek)window)->comment)), &theRect, teJustLeft);
  2736.     HUnlock(((AboutWPeek)window)->comment);
  2737.  
  2738.     UpdateControls(window, window->visRgn);
  2739.     DoButtonOutline(((WindowPeek)window)->controlList);
  2740. }
  2741.  
  2742. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2743. /*
  2744. First thing to do is call KillSound to stop any sound in progress and
  2745. close the status window.  If there’s enough memory available, I’ll play
  2746. the about sound.  This is sound is asynchronous and will automatically be
  2747. disposed of when completed.  There is an icon, taken from the bundle
  2748. resources, and a picture.  The text is taken from a string resource.  It
  2749. contains a couple variables just like ParamText would want.  I get the
  2750. current name of the application from the AppParms.  This is the name of
  2751. the application as specified by the user.  I read in my 'vers' resource
  2752. to get the current version to be displayed in the window.  Read Tech Note
  2753. 189 for more details on the vers resource.  I think these are two
  2754. important things to show in the about box.  These two portions of the text
  2755. are put into place with my own version of ParamText.   I tried all of this
  2756. with a standard dialog, but had trouble.  Sometimes the color icon didn’t
  2757. show up.  Trying to center justify text with a statText item wasn’t really
  2758. possible.  On the Mac SE, for some unknown reason, TESetJust failed to
  2759. center the textH of the dialog.  I also found that this call would set the
  2760. dialog’s text back to Chicago even after I had called TextFont.  So, I
  2761. gave up and did everything myself.  This is a demonstration of how to
  2762. create a dialog without using the Dialog Manager.
  2763. */
  2764.  
  2765. #pragma segment Main
  2766. void DoAbout(void)
  2767. {
  2768.     Str255            verNum;
  2769.     Str255            appName;
  2770.     Ptr                aboutPtr;
  2771.     AboutWPeek        aboutPeek;
  2772.     ControlHandle    control;
  2773.     VersRecHndl        curVersion;
  2774.     OSErr            theErr;
  2775.     Boolean            ignore;
  2776.  
  2777.     KillSound();
  2778.     aboutPtr = NewPtrClear(sizeof(AboutWindow));
  2779.     if (aboutPtr != nil) {
  2780.         aboutPeek = (AboutWPeek)GetNewWindow(rAboutWindow, aboutPtr, (WindowPtr)-1);
  2781.         SetWRefCon((WindowPtr)aboutPeek, rAboutWindow);
  2782.         curVersion = (VersRecHndl)Get1Resource('vers', 1);
  2783.         if (curVersion != nil)
  2784.             PStringCopy((**curVersion).shortVersion, verNum); // get version string
  2785.         else
  2786.             verNum[0] = 0;                                // at least initialize it
  2787.         PStringCopy(LMGetCurApName(), appName);
  2788.         aboutPeek->appPict = Get1Resource('PICT', rAppPict);
  2789.         aboutPeek->comment = Get1Resource('STR ', rAboutText);
  2790.         control = GetNewControl(rAboutOkCntl, (WindowPtr)aboutPeek);
  2791.  
  2792.         if (     (aboutPeek->appPict != nil)
  2793.              && (aboutPeek->comment != nil)
  2794.              && (control != nil))
  2795.         {
  2796.             HNoPurge(aboutPeek->appPict);                // must keep them around
  2797.             HNoPurge(aboutPeek->comment);
  2798.             MyParamText((StringHandle)aboutPeek->comment, appName, verNum);
  2799.             if (!FailLowMemory(0))
  2800.                 theErr = AsynchSndPlay((SndListHandle)Get1Resource(soundListRsrc, rMoofSound));
  2801.         }
  2802.         else                                            // couldn’t build window
  2803.             ignore = DoCloseWindow((WindowPtr)aboutPeek);
  2804.     }
  2805. }
  2806.  
  2807. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2808. /*
  2809. Get the selected sound and pass it to AsynchSndPlay or HyperSndPlay.  This
  2810. depends on the normal flag.  HyperCard’s method is not normal.  This is
  2811. the HyperCard version of playing a sound.  It resamples any sound to
  2812. middle C.  If the resource is too large to fit in memory, I’ll get a nil
  2813. handle error from the SoundUnit.  It might be nice to test for this
  2814. before calling the SoundUnit and telling the user they’re too low on
  2815. memory, but the SoundUnit is robust enough and reports the error.  It’s
  2816. important to call KillSound to dispose of any data that was
  2817. allocated if an error were to occur.
  2818. */
  2819.  
  2820. #pragma segment Main
  2821. void PlaySelectedSnd(SndDocPeek sndDoc, short message)
  2822. {
  2823.     SndListHandle    sndHandle;
  2824.     OSErr            theErr;
  2825.  
  2826.     theErr = GetSelection(sndDoc, &sndHandle);
  2827.     if (theErr == noErr) {
  2828.         if (message == sPlayingMsg)
  2829.             theErr = AsynchSndPlay(sndHandle);
  2830.         else
  2831.             theErr = HyperSndPlay(sndHandle);
  2832.     }
  2833.     if (theErr == noErr) {
  2834.         sndDoc->sndInUse = true;                // this document has a snd in use
  2835.         ShowStatusWindow(message);
  2836.     }
  2837.     else {
  2838.         KillSound();
  2839.         AlertUser(theErr, sSoundErr);
  2840.     }
  2841. }
  2842.  
  2843. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2844. /*
  2845. Given a sound resource ID, this will get my song resource and call the
  2846. SoundUnit to use that sampled sound and song to play a tune.  This
  2847. application will play one of two songs for sampled sounds.  If any error
  2848. is encountered, I call KillSound to dispose of all data.
  2849. */
  2850.  
  2851. #pragma segment Main
  2852. void PlaySndSong(SndDocPeek sndDoc, short sndID)
  2853. {
  2854.     SndChannelPtr    chan;
  2855.     SndListHandle    sndInst;
  2856.     SndListHandle    sndSong;
  2857.     OSErr            theErr;
  2858.  
  2859.     theErr = GetSelection(sndDoc, &sndInst);
  2860.     if (theErr == noErr) {
  2861.         sndSong = (SndListHandle)Get1Resource(soundListRsrc, sndID);
  2862.         theErr = ResError();                        // save any error
  2863.         if (sndSong != nil) {
  2864.             theErr = GetSampleChan(&chan, kInitNone, sndInst);
  2865.             if (theErr == noErr) {
  2866.                 sndDoc->sndInUse = true;            // this document has a snd in use
  2867.                 theErr = PlaySong(chan, sndSong);
  2868.             }
  2869.         }
  2870.     }
  2871.     if (theErr == noErr) {
  2872.         if (sndID == rScaleSnd)
  2873.             ShowStatusWindow(sScaleMsg);
  2874.         else                                        // I can play scales or a melody
  2875.             ShowStatusWindow(sMelodyMsg);
  2876.     }
  2877.     else {                                            // catch any errors
  2878.         KillSound();
  2879.         AlertUser(theErr, sSoundErr);
  2880.     }
  2881. }
  2882.  
  2883. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2884. /*
  2885. Given a sound resource ID, this will get my song resource and call the
  2886. SoundUnit to use the note synthesizer and song to play a tune.  I request
  2887. the note channel’s timbre (sounds like “tom burr”).  If any error is
  2888. encountered, I call KillSound to dispose of all data.
  2889. */
  2890.  
  2891. #pragma segment Main
  2892. void PlaySquareSong(short sndID)
  2893. {
  2894.  
  2895.     SndListHandle    sndSong;
  2896.     SndChannelPtr    chan;
  2897.     OSErr            theErr;
  2898.  
  2899.     sndSong = (SndListHandle)Get1Resource(soundListRsrc, sndID);
  2900.     if (sndSong != nil) {
  2901.         theErr = GetSquareWaveChan(&chan, kPreferredTimbre);
  2902.         if (theErr == noErr) {
  2903.             theErr = PlaySong(chan, sndSong);
  2904.             if (theErr == noErr) {
  2905.                 if (sndID == rScaleSnd)
  2906.                     ShowStatusWindow(sScaleMsg);
  2907.                 else                                // I play scales or a melody
  2908.                     ShowStatusWindow(sMelodyMsg);
  2909.             }
  2910.         }
  2911.         if (theErr != noErr) {                        // catch any errors
  2912.             KillSound();
  2913.             AlertUser(theErr, sSoundErr);
  2914.         }
  2915.     }
  2916.     else
  2917.         AlertUser(ResError(), sResErr);                // I’ll return the resource error
  2918. }
  2919.  
  2920. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2921. /*
  2922. This is a demonstration of the note synth’s tone qualities (or the lack
  2923. there of).  This simply loops through timbres sending alternating note and
  2924. rest commands.  Once all the notes have been sent, then I need to send a
  2925. callBackCmd to signal the SoundUnit to dispose of the channel.  Well,
  2926. actually the SoundUnit will set a global flag that the application will be
  2927. polling for later in the event loop.  Once this happens, or if any errors
  2928. are encountered along the way, KillSound will be called.  One very
  2929. disappointing aspect to changing the timbre is that the Mac Plus or SE
  2930. cannot handle this while a note is sounding.  The Apple Sound Chip can and
  2931. if you wanted to remove the rests try this routine on a Mac II, for
  2932. example, you can hear a continuous note while the timbre changes.  Try
  2933. this on a Mac Plus and you’ll hear garbage.  I’d show this myself, but how
  2934. do I determine if the Mac has the ASC?
  2935.  
  2936. BUG NOTE: There is problem when the final sound command is a freqDurationCmd.
  2937. The note will continue to sound, looping forever, until a quietCmd is sent
  2938. or the channel is disposed of.  To prevent unwanted looping, I send a
  2939. quietCmd after all notes.
  2940. */
  2941.  
  2942. #pragma segment Main
  2943. void PlaySquareTimbres(void)
  2944. {
  2945.     SndChannelPtr    chan;
  2946.     short            timbre;
  2947.     OSErr            theErr;
  2948.  
  2949.     theErr = GetSquareWaveChan(&chan, kPreferredTimbre);
  2950.     if (theErr == noErr) {
  2951.         ShowStatusWindow(sTimbresMsg);
  2952.         for (timbre = kSineWave; timbre <= kSquareWave; timbre += 8) {
  2953.             theErr = SetSquareWaveTimbre(chan, timbre, kWait);
  2954.             if (theErr == noErr)
  2955.                 theErr = SendNote(chan, kOneSecond / 2, kOctave7 + Akey);
  2956.             if (theErr == noErr)
  2957.                 theErr = SendRest(chan, kOneSecond / 10);
  2958.             timbre = timbre + 8;                    // skip a few more timbres
  2959.             if (theErr != noErr)                    // if there was an error...
  2960.                 break;                                // get out of the loop
  2961.         }
  2962.     }
  2963.     if (theErr == noErr)
  2964.         theErr = SoundComplete(chan);
  2965.     else {                                            // catch any errors
  2966.         KillSound();
  2967.         AlertUser(theErr, sSoundErr);
  2968.     }
  2969. }
  2970.  
  2971. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2972. /*
  2973. This demonstrates the wave table synthesizers.  First thing to do is
  2974. obtain a wave cycle and the 'snd ' resource containing a song to be
  2975. played.  Then I’m ready to get the four wave channels and install the
  2976. chosen wave.  Once the wave is installed into the channel I can dispose of
  2977. the memory used to create the wave, since the Sound Manager will copy it
  2978. to its internal buffers.  At this point I’m ready to play the song.  It’s
  2979. not easy to hear four wave synths playing the same note with the same wave
  2980. table.  I was going to add a modifier to the channel that would transpose
  2981. each channels note, but I found a bug.
  2982.  
  2983. BUG NOTE: Installing a modifier to one of the wave table channels caused
  2984. the channel to fail.  My normal sequence of events is this: I synchronize
  2985. the four channels, send all the note commands, end this with the
  2986. callBackCmd, and finally release the channels to play their queues.  When
  2987. I added a modifier, the callBackCmd was the first command to be processed.
  2988. This caused my completion routines to be called and before the channel
  2989. made any sound it was disposed.  I tried this without the callBackCmd and
  2990. the channel never processed any commands.
  2991.  
  2992. BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  2993. chip based Mac.  At least not so far with any System 6.0x releases.  This
  2994. leaves the Mac Plus/SE without four tone polyphonic sound.
  2995.  
  2996. VERSION 1.2: No longer need to call HasWorkingWaveTables since Sound Manager
  2997. 2 and later fixed the problem.
  2998. */
  2999.  
  3000. #pragma segment Main
  3001. void PlayWaveScale(void)
  3002. {
  3003.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3004.     SndListHandle    sndSong;
  3005.     SndListHandle    waveHandle;
  3006.     Ptr                waveTablePtr;
  3007.     long            offSet;
  3008.     short            sndType;
  3009.     short            waveLength;
  3010.     OSErr            theErr;
  3011.  
  3012.     sndSong = (SndListHandle)Get1Resource(soundListRsrc, rScaleSnd);
  3013.     if (sndSong != nil) {
  3014.         waveHandle = (SndListHandle)Get1Resource(soundListRsrc, rTenorVox);
  3015.         theErr = HoldSnd(waveHandle);
  3016.         if (theErr == noErr) {
  3017.             offSet = GetSndDataOffset(waveHandle, &sndType, &waveLength);
  3018.             waveTablePtr = (Ptr)((long)*waveHandle + offSet);
  3019.             theErr = GetWaveChans(&chan1, &chan2, &chan3, &chan4);
  3020.             if (theErr == noErr) {
  3021.                 theErr = InstallWave(chan1, waveTablePtr, waveLength);
  3022.                 if (theErr == noErr) {
  3023.                     theErr = InstallWave(chan2, waveTablePtr, waveLength);
  3024.                     if (theErr == noErr) {
  3025.                         theErr = InstallWave(chan3, waveTablePtr, waveLength);
  3026.                         if (theErr == noErr)
  3027.                             theErr = InstallWave(chan4, waveTablePtr, waveLength);
  3028.                     }
  3029.                 }
  3030.             }
  3031.             HUnlock((Handle)waveHandle);
  3032.             HPurge((Handle)waveHandle);
  3033.             if (theErr == noErr)
  3034.                 theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3035.                                         sndSong, sndSong, sndSong, sndSong);
  3036.             if (theErr == noErr)
  3037.                 ShowStatusWindow(sScaleMsg);
  3038.             else {                                // catch any SoundUnit errors
  3039.                 KillSound();
  3040.                 AlertUser(theErr, sSoundErr);
  3041.             }
  3042.         }
  3043.         else
  3044.             AlertUser(theErr, sResErr);            // couldn’t get waveHandle
  3045.     }
  3046.     else
  3047.         AlertUser(ResError(), sResErr);            // couldn’t get song
  3048. }
  3049.  
  3050. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3051. /*
  3052. This is a utility routine used to obtain the four snd resources that
  3053. contain parts of a song.  Nothing much to do other then get the resource
  3054. and do error checking.
  3055. */
  3056.  
  3057. #pragma segment Main
  3058. OSErr GetSndSongs(short sndSongID1, short sndSongID2,
  3059.                     short sndSongID3, short sndSongID4,
  3060.                     SndListHandle *sndSong1, SndListHandle *sndSong2,
  3061.                     SndListHandle *sndSong3, SndListHandle *sndSong4)
  3062. {
  3063.     OSErr    result = noErr;                            // initialize result
  3064.  
  3065.     // get all the snds
  3066.     *sndSong1 = (SndListHandle)Get1Resource(soundListRsrc, sndSongID1);
  3067.     if (sndSong1 != nil) {
  3068.         *sndSong2 = (SndListHandle)Get1Resource(soundListRsrc, sndSongID2);
  3069.         if (sndSong2 != nil) {
  3070.             *sndSong3 = (SndListHandle)Get1Resource(soundListRsrc, sndSongID3);
  3071.             if (sndSong3 != nil)
  3072.                 *sndSong4 = (SndListHandle)Get1Resource(soundListRsrc, sndSongID4);
  3073.         }
  3074.     }
  3075.     if ((sndSong1 == nil) || (sndSong2 == nil)
  3076.      || (sndSong3 == nil) || (sndSong4 == nil))
  3077.         result = ResError();                        // return resource error
  3078.     return (result);
  3079. }
  3080.  
  3081. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3082. /*
  3083. This routine is a utility I’m using to prepare four wave table channels.
  3084. First thing to do is obtain a wave table data I stored in a set of 'snd '
  3085. resources.  Then I’m ready to install these wave tables into the four wave
  3086. channels.  Once the waves are installed into the channel I can dispose of
  3087. the memory used to create each wave, since the Sound Manager will copy
  3088. them to its internal buffers.  At this point the channels are ready to
  3089. play sounds.
  3090. */
  3091.  
  3092. #pragma segment Main
  3093. OSErr InstallWaveSnds(SndChannelPtr chan1, SndChannelPtr chan2,
  3094.                       SndChannelPtr chan3, SndChannelPtr chan4,
  3095.                       short waveID1, short waveID2, short waveID3, short waveID4)
  3096. {
  3097.     SndListHandle    waveSnd1, waveSnd2, waveSnd3, waveSnd4;
  3098.     Ptr                wavePtr;
  3099.     long            offSet;
  3100.     short            waveLgth;
  3101.     short            sndType;
  3102.     OSErr            theErr;
  3103.  
  3104.     // get em and hold em down
  3105.     waveSnd1 = (SndListHandle)Get1Resource(soundListRsrc, waveID1);
  3106.     theErr = HoldSnd(waveSnd1);
  3107.     if (theErr == noErr) {
  3108.         waveSnd2 = (SndListHandle)Get1Resource(soundListRsrc, waveID2);
  3109.         theErr = HoldSnd(waveSnd2);
  3110.         if (theErr == noErr) {
  3111.             waveSnd3 = (SndListHandle)Get1Resource(soundListRsrc, waveID3);
  3112.             theErr = HoldSnd(waveSnd3);
  3113.             if (theErr == noErr) {
  3114.                 waveSnd4 = (SndListHandle)Get1Resource(soundListRsrc, waveID4);
  3115.                 theErr = HoldSnd(waveSnd4);
  3116.             }
  3117.         }
  3118.     }
  3119.     if (theErr != noErr)
  3120.         return (theErr);                            // we’re out of here
  3121.                                                     // catch the waves
  3122.     offSet = GetSndDataOffset(waveSnd1, &sndType, &waveLgth);
  3123.     wavePtr = (Ptr)((long)*waveSnd1 + offSet);
  3124.     theErr = InstallWave(chan1, wavePtr, waveLgth);
  3125.     if (theErr == noErr) {
  3126.         offSet = GetSndDataOffset(waveSnd2, &sndType, &waveLgth);
  3127.         wavePtr = (Ptr)((long)*waveSnd1 + offSet);
  3128.         theErr = InstallWave(chan2, wavePtr, waveLgth);
  3129.         if (theErr == noErr) {
  3130.             offSet = GetSndDataOffset(waveSnd3, &sndType, &waveLgth);
  3131.             wavePtr = (Ptr)((long)*waveSnd1 + offSet);
  3132.             theErr = InstallWave(chan3, wavePtr, waveLgth);
  3133.             if (theErr == noErr) {
  3134.                 offSet = GetSndDataOffset(waveSnd4, &sndType, &waveLgth);
  3135.                 wavePtr = (Ptr)((long)*waveSnd1 + offSet);
  3136.                 theErr = InstallWave(chan4, wavePtr, waveLgth);
  3137.             }
  3138.         }
  3139.     }
  3140.     HUnlock((Handle)waveSnd1);                        // done with resources
  3141.     HPurge((Handle)waveSnd1);
  3142.     HUnlock((Handle)waveSnd2);
  3143.     HPurge((Handle)waveSnd2);
  3144.     HUnlock((Handle)waveSnd3);
  3145.     HPurge((Handle)waveSnd3);
  3146.     HUnlock((Handle)waveSnd4);
  3147.     HPurge((Handle)waveSnd4);
  3148.     return (theErr);                                // return the error
  3149. }
  3150.  
  3151. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3152. /*
  3153. This is the demonstration of the wave table synthesizers.  This will get
  3154. four snd resources that contain parts to a song.  Then I get the four wave
  3155. table channels.  With these four channels, I install two other snd
  3156. resources that contain wave table data.  Once the four songs, four
  3157. channels, and two wave tables are ready then I play the song.
  3158.  
  3159. BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  3160. chip based Mac.  At least not so far with any System 6.0x release.  This
  3161. leaves the Mac Plus/SE without four tone polyphonic sound.
  3162.  
  3163. VERSION 1.2: No longer need to call HasWorkingWaveTables since Sound Manager
  3164. 2 and later fixed the problem.
  3165. */
  3166.  
  3167. #pragma segment Main
  3168. void PlayWaveMelody(void)
  3169. {
  3170.     SndListHandle    sndSong1, sndSong2, sndSong3, sndSong4;
  3171.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3172.     OSErr            theErr;
  3173.  
  3174.     theErr = GetSndSongs(rMelodyPart1, rMelodyPart2, rMelodyPart3, rMelodyPart4,
  3175.                                 &sndSong1, &sndSong2, &sndSong3, &sndSong4);
  3176.     if (theErr != noErr) {
  3177.         AlertUser(theErr, sResErr);                // return the error
  3178.         return;                                    // we’re out of here
  3179.     }
  3180.     theErr = GetWaveChans(&chan1, &chan2, &chan3, &chan4);
  3181.     if (theErr == noErr) {
  3182.         theErr = InstallWaveSnds(chan1, chan2, chan3, chan4,
  3183.                             rWaveMelody, rWaveHarmony, rWaveHarmony, rWaveHarmony);
  3184.         if (theErr == noErr)
  3185.             theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3186.                                         sndSong1, sndSong2, sndSong3, sndSong4);
  3187.     }
  3188.     if (theErr == noErr)
  3189.         ShowStatusWindow(sMelodyMsg);
  3190.     else {                                        // catch any errors
  3191.         KillSound();
  3192.         AlertUser(theErr, sSoundErr);
  3193.     }
  3194. }
  3195.  
  3196. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3197. /*
  3198. This is the demonstration of the wave table synthesizers.  This will get
  3199. four snd resources that contain parts to a song.  Then I get the four wave
  3200. table channels.  With these four channels, I install four other snd resources
  3201. that contain wave table data.  Once the four songs, four channels, and
  3202. four wave tables are ready then I play the song.  By the way, SATB stands
  3203. for Soprano, Alto, Tenor, and Bass.  It’s standard music-speak.
  3204.  
  3205. BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  3206. chip based Mac.  At least not so far with any System 6.0x release.  This
  3207. leaves the Mac Plus/SE without four tone polyphonic sound.
  3208.  
  3209. VERSION 1.2: No longer need to call HasWorkingWaveTables since Sound Manager
  3210. 2 and later fixed the problem.
  3211. */
  3212.  
  3213. #pragma segment Main
  3214. void PlayWaveSATB(void)
  3215. {
  3216.     SndListHandle    sndSong1, sndSong2, sndSong3, sndSong4;
  3217.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3218.     OSErr            theErr;
  3219.  
  3220.     theErr = GetSndSongs(rCounterPt1, rCounterPt2, rCounterPt3, rCounterPt4,
  3221.                                 &sndSong1, &sndSong2, &sndSong3, &sndSong4);
  3222.     if (theErr != noErr) {
  3223.         AlertUser(theErr, sResErr);                    // return the error
  3224.         return;                                        // we’re out of here
  3225.     }
  3226.     theErr = GetWaveChans(&chan1, &chan2, &chan3, &chan4);
  3227.     if (theErr == noErr) {
  3228.         theErr = InstallWaveSnds(chan1, chan2, chan3, chan4,
  3229.                                     rSopranoVox, rAltoVox, rTenorVox, rBassVox);
  3230.         if (theErr == noErr)
  3231.             theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3232.                                         sndSong1, sndSong2, sndSong3, sndSong4);
  3233.     }
  3234.     if (theErr == noErr)
  3235.         ShowStatusWindow(sCounterPtMsg);
  3236.     else {                                            // catch any errors
  3237.         KillSound();
  3238.         AlertUser(theErr, sSoundErr);
  3239.     }
  3240. }
  3241.  
  3242. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3243. /*
  3244. VERSION 1.2: Create four sample sound channels with an instrument sound
  3245. installed in each one. Then play the four part song to demonstrate the
  3246. sample sound channel.
  3247. */
  3248.  
  3249. #pragma segment Main
  3250. void PlaySampleSATB(void)
  3251. {
  3252.     SndListHandle    sndSong1, sndSong2, sndSong3, sndSong4;
  3253.     SndListHandle    sampleHarmony;
  3254.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3255.     OSErr            theErr;
  3256.  
  3257.     theErr = GetSndSongs(rCounterPt1, rCounterPt2, rCounterPt3, rCounterPt4,
  3258.                                 &sndSong1, &sndSong2, &sndSong3, &sndSong4);
  3259.     if (theErr != noErr) {
  3260.         AlertUser(theErr, sResErr);                    // return the error
  3261.         return;                                        // we’re out of here
  3262.     }
  3263.  
  3264.     sampleHarmony = (SndListHandle)Get1Resource(soundListRsrc, rSampleHarmony);
  3265.     theErr = Get4SampleInstruments(&chan1, &chan2, &chan3, &chan4,
  3266.                             sampleHarmony, sampleHarmony, sampleHarmony, sampleHarmony);
  3267.     if (theErr == noErr)
  3268.         theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3269.                                 sndSong1, sndSong2, sndSong3, sndSong4);
  3270.     if (theErr == noErr)
  3271.         ShowStatusWindow(sCounterPtMsg);
  3272.     else                                            // catch any errors
  3273.     {
  3274.         KillSound();
  3275.         AlertUser(theErr, sSoundErr);
  3276.     }
  3277. }
  3278.  
  3279. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3280. /*
  3281. VERSION 1.2: Create four sample sound channels with an instrument sound
  3282. installed in each one. Then play the four part song to demonstrate the
  3283. sample sound channel.
  3284. */
  3285.  
  3286. #pragma segment Main
  3287. void PlaySampleMelody(void)
  3288. {
  3289.     SndListHandle    sndSong1, sndSong2, sndSong3, sndSong4;
  3290.     SndListHandle    sampleHarmony, sampleMelody;
  3291.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3292.     OSErr            theErr;
  3293.  
  3294.     theErr = GetSndSongs(rMelodyPart1, rMelodyPart2, rMelodyPart3, rMelodyPart4,
  3295.                                 &sndSong1, &sndSong2, &sndSong3, &sndSong4);
  3296.     if (theErr != noErr) {
  3297.         AlertUser(theErr, sResErr);                    // return the error
  3298.         return;                                        // we’re out of here
  3299.     }
  3300.  
  3301.     sampleHarmony = (SndListHandle)Get1Resource(soundListRsrc, rSampleHarmony);
  3302.     sampleMelody = (SndListHandle)Get1Resource(soundListRsrc, rSampleMelody);
  3303.     theErr = Get4SampleInstruments(&chan1, &chan2, &chan3, &chan4,
  3304.                             sampleMelody, sampleHarmony, sampleHarmony, sampleHarmony);
  3305.     if (theErr == noErr)
  3306.         theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3307.                                 sndSong1, sndSong2, sndSong3, sndSong4);
  3308.     if (theErr == noErr)
  3309.         ShowStatusWindow(sMelodyMsg);
  3310.     else                                            // catch any errors
  3311.     {
  3312.         KillSound();
  3313.         AlertUser(theErr, sSoundErr);
  3314.     }
  3315. }
  3316.  
  3317. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3318. /*
  3319. VERSION 1.1:  This is just one of the reasons I hate the Dialog Manager.
  3320. I needed a simple dialog to ask the user for a name for their new sound.
  3321. To do this, I only needed a simple dialog with two buttons and an
  3322. editable text item.  Since the ModalDialog will not draw an outline
  3323. around the default item, I then needed an userItem.  This is the really
  3324. stupid part. The userItem is only there just to get a chance to draw an
  3325. outline around the default button.  It has no other purpose.  It is not
  3326. visible, not does it get any user interaction what so ever.  It's just a
  3327. pain in the ass.
  3328. */
  3329.  
  3330. #pragma segment Main
  3331. pascal void DefaultOutline(WindowPtr window, short theItem)
  3332. {
  3333. #pragma unused (theItem)
  3334.     Handle itemHndl;
  3335.     Rect itemRect;
  3336.     short kind;
  3337.  
  3338.     GetDialogItem((DialogPtr)window, ok, &kind, &itemHndl, &itemRect);
  3339.     DoButtonOutline((ControlHandle)itemHndl);
  3340. }
  3341.  
  3342. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3343. /*
  3344. VERSION 1.1:  Show a dialog asking the user to name their new sound
  3345. resource.  I need to outline the default button, so I have to install an
  3346. userItem setting its drawing procedure to do the outline around a
  3347. different item altogether.  The Dialog Manager really bugs me.
  3348. */
  3349.  
  3350. #pragma segment Main
  3351. void GetSndName(Str255 sndName)
  3352. {
  3353.     DialogPtr dialog;
  3354.     Handle itemHndl;
  3355.     Rect itemRect;
  3356.     short kind;
  3357.     short theItem;
  3358.  
  3359.     dialog = GetNewDialog(rGetNameDLOG, nil, (WindowPtr)-1);
  3360.     GetDialogItem(dialog, rUserItem, &kind, &itemHndl, &itemRect);
  3361.     SetDialogItem(dialog, rUserItem, kind, (Handle)DefaultOutline, &itemRect);
  3362.     do
  3363.         ModalDialog(nil, &theItem);
  3364.     while ((theItem != ok) && (theItem != cancel));
  3365.     if (theItem == ok) {
  3366.         GetDialogItem(dialog, rNameItem, &kind, &itemHndl, &itemRect);
  3367.         GetDialogItemText(itemHndl, sndName);
  3368.     } else
  3369.         sndName[0] = 0;
  3370.     DisposeDialog(dialog);
  3371. }
  3372.  
  3373. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3374. /*
  3375. VERSION 1.1:  This routine adds the given snd resource to the file and
  3376. document. First thing to do is find a proper resource ID for the 'snd '.
  3377. There is a reserved range for them, didn't you read the documentation?
  3378. Once this new resource is added then I update the file and re-build the
  3379. list of sounds.  This is necessary since the list must be in the same
  3380. order as the sounds are in the file.  I ignore the error returned by
  3381. InitSndList, since the chances of it failing at this point are slim.  If
  3382. anything is wrong with the list, then the rest of this application is
  3383. robust enough to handle a resource problem.  The user would have to close
  3384. the document and attempt to open it again.  If adding the resources
  3385. works, but updating the file fails then I will remove it.  This keeps the
  3386. document consistent with the file.
  3387. */
  3388.  
  3389. #pragma segment Main
  3390. OSErr AddSnd(SndDocPeek sndDoc, StringPtr sndNamePtr, SndListHandle sndHndl)
  3391. {
  3392.     short resID;
  3393.     OSErr theErr;
  3394.     short ignore;
  3395.  
  3396.     UseResFile(sndDoc->resFile);                //put our resource in the right file
  3397.     do
  3398.         resID = Unique1ID(soundListRsrc);
  3399.     while (resID < kSystemSndRange);
  3400.     AddResource((Handle)sndHndl, soundListRsrc, resID, sndNamePtr);
  3401.     theErr = ResError();
  3402.     UseResFile(gAppResRef);                        //restore our resource file
  3403.     if (theErr == noErr) {
  3404.         UpdateResFile(sndDoc->resFile);            //update the file
  3405.         theErr = ResError();
  3406.         if (theErr == noErr) {
  3407.             ignore = FlushVol(nil, sndDoc->vRefNum);
  3408.             LDelRow(0, 0, sndDoc->list);        //delete all the rows
  3409.             ignore = InitSndList(sndDoc);        //re-create the list
  3410.             SelectSndCell(sndDoc, resID);        //select the new snd
  3411.         } else
  3412.             RemoveResource((Handle)sndHndl);    //couldn't add it, update failed
  3413.     }
  3414.     return(theErr);
  3415. }
  3416.  
  3417. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3418. /*
  3419. VERSION 1.1:  This routine has one tricky aspect involving the Resource
  3420. Manager and removing a resource.  There's a catch.  I want the document
  3421. to always reflect the contents of the file on disk.  In other words,
  3422. InitSndList depends on UpdateResFile returning noErr.  If the file is
  3423. locked, then removing a resource shouldn't be allowed but RmveResource
  3424. will return noErr even if the file cannot be updated.  This is a
  3425. "feature" since the user may unlock the volume after removing the
  3426. resource and then UpdateResFile would work.  If RmveResource succeeds,
  3427. but UpdateResFile fails then the resource map in memory will be
  3428. inconsistent with what's on disk.  If the user then closed the document
  3429. and opened it again, the resource they just removed would magically still
  3430. be there.  The basic problem is that it is difficult to determine if a
  3431. given file will really allow write access.  There's at least three
  3432. situations to check: a locked file, a locked volume, or an AppleShare
  3433. folder privileges issue.  The ideal, and probably the best, solution
  3434. would be to deselect the edit commands from the user for a read-only
  3435. file.  This would involve lots of File Manager calls every time the user
  3436. selects a menu command.  (If you thought that GetFCBInfo would tell you
  3437. this, you're wrong.  You can have write permission to a file that is on a
  3438. locked volume.)  Additionally, the user needs to see that the reason the
  3439. edit menu doesn't work is because the file is read-only which would
  3440. require another feature to be added with lots more code.  This is why I
  3441. call ChangedResource before any other Resource Manager calls.
  3442. ChangedResource will determine if the resource can be written to disk.
  3443. If not, then it returns an error which is exactly what I wanted to know
  3444. in the first place.  I want to flush the cache to keep the disk's
  3445. resource map consistent with the resource data.  Otherwise, a crash could
  3446. occur the resource fork might be damaged and the file has to be repaired
  3447. (if possible) or deleted.  I'm ignoring the InitSndList result.  At this
  3448. stage, there's only a slim chance the list couldn't be re-built.  If it
  3449. does fail, the file should be closed.
  3450.  
  3451. A tip to the reader: dispose of as much memory as possible before calling
  3452. UpdateResFile.  This makes it faster.  UpdateResFile will not purge any
  3453. memory, but only attempts to use the available space.  If there's little
  3454. free space then UpdateResFile will run really slow.
  3455. */
  3456.  
  3457. #pragma segment Main
  3458. void ClearSnd(SndDocPeek sndDoc)
  3459. {
  3460.     SndListHandle    sndHndl;
  3461.     OSErr            theErr;
  3462.     short            ignore;
  3463.  
  3464.     theErr = GetSelection(sndDoc, &sndHndl);            //get the resource to remove
  3465.     if (theErr == noErr) {
  3466.         ChangedResource((Handle)sndHndl);                //can we change the file?
  3467.         theErr = ResError();                            //save the error result
  3468.         if (theErr == noErr) {
  3469.             UseResFile(sndDoc->resFile);                //use the right resource file
  3470.             RemoveResource((Handle)sndHndl);            //remove that sucker
  3471.             theErr = ResError();                        //save the error result
  3472.             UseResFile(gAppResRef);                        //restore our resource file
  3473.             if (theErr == noErr) {
  3474.                 DisposeHandle((Handle)sndHndl);            //get rid of the memory
  3475.                 UpdateResFile(sndDoc->resFile);            //update the file
  3476.                 theErr = ResError();                    //save the error result
  3477.                 if (theErr == noErr)
  3478.                     ignore = FlushVol(nil, sndDoc->vRefNum);
  3479.                 LDelRow(0, 0, sndDoc->list);            //delete all the rows
  3480.                 ignore = InitSndList(sndDoc);            //re-create the list
  3481.                 SelectNextCell(sndDoc->list, true);     //select the first cell
  3482.                 ActivateSndCntls(sndDoc);                //may not be any sounds left
  3483.             }
  3484.         }
  3485.     }
  3486.     if (theErr != noErr)
  3487.         AlertUser(theErr, sEditErr);
  3488. }
  3489.  
  3490. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3491. /*
  3492. VERSION 1.1:  This routine will create a handle and record sound into it.
  3493. A new sound will prompt the user for a name to add it to the document.
  3494. The Sound Input Manager will re-size this handle to be as small as
  3495. possible to contain only the samples recorded.  You can pass sndHandl ==
  3496. nil to SndRecord, which will cause the Sound Input Manager to create a
  3497. handle for you.  If adding the new sound is successful, the new resource
  3498. handle is marked purgeable, because I only use them temporally and they
  3499. tend to be large.  I have to set the sndHandle variable to nil in this
  3500. case since it is now belongs to the Resource Manager and I don't want to
  3501. dispose of it in the error handling code.  The choice of recording
  3502. quality wasn't given to the user.  Typically, users would only be
  3503. confused by the question of "what compression ratio do you prefer?"  As
  3504. a power user option, it would be nice to let the user set the rate.  Be
  3505. careful since this is a user interface issue, and Apple expects to see
  3506. lots of Sound Input features in applications.
  3507. */
  3508.  
  3509. #pragma segment Main
  3510. void DoRecordSound(SndDocPeek sndDoc)
  3511. {
  3512.     Str255            sndName;
  3513.     Point            recTopLeft;
  3514.     long            total;
  3515.     long            contig;
  3516.     SndListHandle    sndHandle;
  3517.     OSErr            theErr;
  3518.  
  3519.     KillSound();
  3520.     PurgeSpace(&total, &contig);
  3521.     sndHandle = (SndListHandle)NewHandle(contig - kMinSpace);
  3522.     if (sndHandle != nil) {
  3523.         recTopLeft.v = kRecordTop;
  3524.         recTopLeft.h = kRecordLeft;
  3525.         theErr = SndRecord(nil, recTopLeft, siBestQuality, &sndHandle);
  3526.         if (theErr == noErr) {
  3527.             GetSndName(sndName);
  3528.             theErr = AddSnd(sndDoc, sndName, sndHandle);
  3529.             if (theErr == noErr) {
  3530.                 HPurge((Handle)sndHandle);
  3531.                 sndHandle = nil;
  3532.             }
  3533.         }
  3534.     } else
  3535.         theErr = MemError();
  3536.     if (sndHandle != nil)
  3537.         DisposeHandle((Handle)sndHandle);
  3538.     if ((theErr != noErr) && (theErr != userCanceledErr))
  3539.         AlertUser(theErr, sSoundErr);
  3540. }
  3541.  
  3542. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3543. /*
  3544. Enable and disable menus based on the current state.  The user can only
  3545. select enabled menu items so I set up all the menu items before calling
  3546. MenuSelect or MenuKey, since these are the only times that a menu item
  3547. can be selected. Note that MenuSelect is also the only time the user will
  3548. see menu items. This approach to deciding what enable/disable state a menu
  3549. item has the advantage of concentrating all the decision making in one
  3550. routine, as opposed to being spread throughout the application.  Other
  3551. application designs may take a different approach that may or may not be
  3552. just as valid.
  3553. */
  3554.  
  3555. #pragma segment Main
  3556. void AdjustMenus(void)
  3557. {
  3558.      MenuHandle menu;
  3559.     WindowPtr window;
  3560.     Boolean allowEdit;
  3561.  
  3562.     window = FrontWindow();
  3563.     menu = GetMenuHandle(mFile);                    //the File menu and items
  3564.     if (IsDAWindow(window) || IsDocWindow(window))
  3565.         EnableItem(menu, iClose);
  3566.     else
  3567.         DisableItem(menu, iClose);
  3568.  
  3569.     menu = GetMenuHandle(mEdit);                    //the Edit menu and items
  3570.     allowEdit = IsDAWindow(window);
  3571.     if (allowEdit)                                    //check the undo item
  3572.         EnableItem(menu, iUndo);
  3573.     else
  3574.         DisableItem(menu, iUndo);
  3575.  
  3576.     if (IsDocWindow(window)) {                        //handle the other edit items
  3577.         allowEdit = HasSelection((SndDocPeek)window) || allowEdit;
  3578.         EnableItem(menu, iPaste);
  3579.     } else
  3580.         DisableItem(menu, iPaste);
  3581.  
  3582.     if (allowEdit) {
  3583.         EnableItem(menu, iCut);
  3584.         EnableItem(menu, iCopy);
  3585.         EnableItem(menu, iClear);
  3586.     } else {
  3587.         DisableItem(menu, iCut);
  3588.         DisableItem(menu, iCopy);
  3589.         DisableItem(menu, iClear);
  3590.     }
  3591. }
  3592.  
  3593. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3594. /*
  3595. VERSION 1.1:  Get the currently selected item and copy it to the
  3596. clipboard.  I want to also save the name for this resource, so I add a
  3597. string type to the clipboard as well.
  3598. */
  3599.  
  3600. #pragma segment Main
  3601. void CopySnd(SndDocPeek sndDoc)
  3602. {
  3603.     Str255            sndName;
  3604.     ResType            rType;
  3605.     SndListHandle    sndHndl;
  3606.     long            scrapLen;
  3607.     short            id;
  3608.     OSErr            theErr;
  3609.  
  3610.     theErr = GetSelection(sndDoc, &sndHndl);
  3611.     if (theErr == noErr) {
  3612.         GetResInfo((Handle)sndHndl, &id, &rType, sndName);
  3613.         scrapLen = ZeroScrap();                        //ignoring the result
  3614.         theErr = PutScrap(StrLength(sndName) + 1, 'STR ', sndName);
  3615.         HLock((Handle)sndHndl);
  3616.         theErr = PutScrap(GetHandleSize((Handle)sndHndl), soundListRsrc, (Ptr)(*sndHndl));
  3617.         HUnlock((Handle)sndHndl);
  3618.         HPurge((Handle)sndHndl);
  3619.     }
  3620.     if (theErr != noErr)
  3621.         AlertUser(theErr, sEditErr);
  3622. }
  3623.  
  3624. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3625. /*
  3626. VERSION 1.1:  Copy the selection and then delete it.
  3627. */
  3628.  
  3629. #pragma segment Main
  3630. void CutSnd(SndDocPeek sndDoc)
  3631. {
  3632.     CopySnd(sndDoc);
  3633.     ClearSnd(sndDoc);
  3634. }
  3635.  
  3636. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3637. /*
  3638. VERSION 1.1:  This routine will create a new resource into the file
  3639. containing the clipboard's sound data.  A name is attempted to be found
  3640. by first checking for the string type in the scrap.  This application
  3641. will always put both a string and a sound together on the clipboard.  But
  3642. if the user copied a sound from the Sound cdev, ResEdit, or by some other
  3643. method then I'll ask the user for a new name.  If adding the new resource
  3644. is successful, then I mark the resource as purgeable and set the sndHndl
  3645. variable to NIL.  The Resource Manager then owns the handle and I don't
  3646. want my error handling to dispose of this new handle.
  3647. */
  3648.  
  3649. #pragma segment Main
  3650. void PasteSnd(SndDocPeek sndDoc)
  3651. {
  3652.     Str255            sndName;
  3653.     StringHandle    sndNameHndl;
  3654.     long            offset;
  3655.     long            scrapLen;
  3656.     SndListHandle    sndHndl;
  3657.     OSErr            theErr;
  3658.  
  3659.     sndHndl = (SndListHandle)NewHandle(0);
  3660.     sndNameHndl = NewString("\p");
  3661.     theErr = MemError();
  3662.     scrapLen = GetScrap((Handle)sndNameHndl, 'STR ', &offset);
  3663.     scrapLen = GetScrap((Handle)sndHndl, soundListRsrc, &offset);
  3664.     if (scrapLen > 0) {
  3665.         if (sndNameHndl != nil)
  3666.             PStringCopy(*sndNameHndl, sndName);
  3667.         else
  3668.             sndName[0] = 0;
  3669.         if (StrLength(sndName) == 0)
  3670.             GetSndName(sndName);
  3671.         theErr = AddSnd(sndDoc, sndName, sndHndl);
  3672.         if (theErr == noErr) {
  3673.             HPurge((Handle)sndHndl);
  3674.             sndHndl = nil;                                        //done with handle
  3675.             ActivateSndCntls(sndDoc);
  3676.         }
  3677.     } else
  3678.         theErr = scrapLen;
  3679.  
  3680.     if (sndHndl != nil)
  3681.         DisposeHandle((Handle)sndHndl);
  3682.     if (sndNameHndl != nil)
  3683.         DisposeHandle((Handle)sndNameHndl);
  3684.     if (theErr != noErr)
  3685.         AlertUser(theErr, sEditErr);
  3686. }
  3687.  
  3688. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3689. /*
  3690. This is called when an item is chosen from the menu bar (after calling
  3691. MenuSelect or MenuKey). It performs the right operation for each command.
  3692. It is good to have both the result of MenuSelect and MenuKey go to
  3693. one routine like this to keep everything organized.
  3694.  
  3695. VERSION 1.1:  Supporting the edit commands for snd resources.
  3696. */
  3697.  
  3698. #pragma segment Main
  3699. void DoMenuCommand(long menuResult)
  3700. {
  3701.     WindowPtr window;
  3702.     short menuID;
  3703.     short menuItem;                            //resource ID and item of the selected menu
  3704.     short daRefNum;
  3705.     Str255 daName;
  3706.     Boolean ignore;
  3707.  
  3708.     menuID = HighWord(menuResult);            //use macros for efficiency...
  3709.     menuItem = LowWord(menuResult);            //to get menu item number and menu number
  3710.     switch (menuID) {
  3711.  
  3712.         case mApple:
  3713.             switch (menuItem) {
  3714.                 case iAbout:                //bring up alert for About
  3715.                     DoAbout();
  3716.                     break;
  3717.                 default:                    //all non-About items in this menu are DAs
  3718.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  3719.                     daRefNum = OpenDeskAcc(daName);
  3720.                     break;
  3721.             }
  3722.             break;
  3723.  
  3724.         case mFile:
  3725.             switch (menuItem) {
  3726.                 case iNew:
  3727.                     NewSoundDoc();
  3728.                     break;
  3729.                 case iOpen:
  3730.                     GetSoundDoc();
  3731.                     break;
  3732.                 case iClose:
  3733.                     ignore = DoCloseWindow(FrontWindow()); //I don’t care if cancelled
  3734.                     break;
  3735.                 case iQuit:
  3736.                     Terminate();
  3737.                     break;
  3738.             }
  3739.             break;
  3740.  
  3741.         case mEdit:                                //call SystemEdit for DA editing && MultiFinder
  3742.             if (! SystemEdit(menuItem - 1)) {    //since I don’t do any editing
  3743.                 window = FrontWindow();
  3744.                 if (IsDocWindow(window)) {
  3745.                     switch (menuItem) {
  3746.  
  3747.                         case iCut:
  3748.                             CutSnd((SndDocPeek)window);
  3749.                             break;
  3750.                         case iCopy:
  3751.                             CopySnd((SndDocPeek)window);
  3752.                             break;
  3753.                         case iPaste:
  3754.                             PasteSnd((SndDocPeek)window);
  3755.                             break;
  3756.                         case iClear:
  3757.                             ClearSnd((SndDocPeek)window);
  3758.                             break;
  3759.                     }
  3760.                 }
  3761.             }
  3762.             break;
  3763.  
  3764.         case mDemos:
  3765.             switch (menuItem) {
  3766.  
  3767.                 case iCheckVolume:
  3768.                     CheckSoundVolume();
  3769.                     break;
  3770.  
  3771.                 case iSquareScale:
  3772.                     PlaySquareSong(rScaleSnd);
  3773.                     break;
  3774.  
  3775.                 case iSquareMelody:
  3776.                     PlaySquareSong(rMelodyPart1);
  3777.                     break;
  3778.  
  3779.                 case iSquareTimbre:
  3780.                     PlaySquareTimbres();
  3781.                     break;
  3782.  
  3783.                 case iWaveScale:
  3784.                     PlayWaveScale();
  3785.                     break;
  3786.  
  3787.                 case iWaveMelody:
  3788.                     PlayWaveMelody();
  3789.                     break;
  3790.  
  3791.                 case iWaveSATB:
  3792.                     PlayWaveSATB();
  3793.                     break;
  3794.  
  3795.                 case iSampleMelody:
  3796.                     PlaySampleMelody();
  3797.                     break;
  3798.  
  3799.                 case iSampleSATB:
  3800.                     PlaySampleSATB();
  3801.                     break;
  3802.  
  3803.             } //switch (menuItem)
  3804.  
  3805.     } //switch (menuID)
  3806.     HiliteMenu(0);                        //unhighlight what MenuSelect or MenuKey hilited
  3807. }
  3808.  
  3809. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3810. /*
  3811. Draw the contents of the application window in response to an update
  3812. event.  At this point, BeginUpdate has been called which sets the window’s
  3813. visRgn to clip drawing only where it needs to be done.  I have the
  3814. controls to draw, a list to update, and a default button to outline.  I
  3815. use UpdateControls to avoid needless drawing that happens with DrawControls.
  3816. It not only runs faster but doesn’t flicker.
  3817. */
  3818.  
  3819. #pragma segment Main
  3820. void DrawSndWindow(WindowPtr window)
  3821. {
  3822.     ControlHandle control;
  3823.     Rect theRect;
  3824.  
  3825.     PenNormal();
  3826.     LUpdate(window->visRgn, ((SndDocPeek)window)->list);    // update list
  3827.     theRect = (**((SndDocPeek)window)->list).rView;            // frame the list
  3828.     theRect.right = theRect.right + kScrollbarAdjust;
  3829.     InsetRect(&theRect, kListFrameInset, kListFrameInset);
  3830.     FrameRect(&theRect);
  3831.     UpdateControls(window, window->visRgn);                    // update controls
  3832.     control = ((WindowPeek)window)->controlList;            // draw button outline
  3833.     while (control != nil) {
  3834.         if (GetControlReference(control) == rPlaySndCntl)
  3835.             DoButtonOutline(control);
  3836.         control = (**control).nextControl;
  3837.     }
  3838. }
  3839.  
  3840. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3841. /*
  3842. When the user types a key, I check if it is one that I’m looking for.
  3843. This routine only handles the non-command key events.  Here I’m looking
  3844. for a arrow key or the return and enter keys for the default button.
  3845.  
  3846. VERSION 1.1: The enter and return keys only work if there is a selection.
  3847. Now supporting the backspace and delete keys which clear the selection.
  3848. */
  3849.  
  3850. #pragma segment Main
  3851. void DoKeyDown(char key, WindowPtr window)
  3852. {
  3853.     ControlHandle control;
  3854.     Boolean ignore;
  3855.  
  3856.     switch (GetWRefCon(window)) {
  3857.  
  3858.         case rSoundWindow:
  3859.             switch (key) {
  3860.  
  3861.                 case kEnterKey:
  3862.                 case kReturnKey:
  3863.                     if (HasSelection((SndDocPeek)window)) {
  3864.                         control = ((WindowPeek)window)->controlList;
  3865.                         while (control != nil) {            //find the default button
  3866.                             if (GetControlReference(control) == rPlaySndCntl)
  3867.                                 SelectButton(control);            //here it is
  3868.                             control = (**control).nextControl;
  3869.                         }
  3870.                         PlaySelectedSnd((SndDocPeek)window, sPlayingMsg);
  3871.                     }
  3872.                     break;
  3873.  
  3874.                 case kUpArrow:
  3875.                     SelectNextCell(((SndDocPeek)window)->list, false);
  3876.                     ActivateSndCntls((SndDocPeek)window);
  3877.                     break;
  3878.  
  3879.                 case kDownArrow:
  3880.                     SelectNextCell(((SndDocPeek)window)->list, true);
  3881.                     ActivateSndCntls((SndDocPeek)window);
  3882.                     break;
  3883.  
  3884.                 case kBackspace:
  3885.                     ClearSnd((SndDocPeek)window);
  3886.                     break;
  3887.             }
  3888.             break; //rSoundWindow
  3889.  
  3890.         case rStatusWindow:
  3891.             if (    (key == kEnterKey)
  3892.                  || (key == kReturnKey)
  3893.                  || (key == kEscape) ) {
  3894.                 SelectButton(((WindowPeek)window)->controlList);
  3895.                 KillSound();
  3896.             }
  3897.             break;
  3898.  
  3899.         case rAboutWindow:
  3900.             if (    (key == kEnterKey)
  3901.                  || (key == kReturnKey)
  3902.                  || (key == kEscape) ) {
  3903.                 SelectButton(((WindowPeek)window)->controlList);
  3904.                 ignore = DoCloseWindow(window);
  3905.             }
  3906.             break;
  3907.     } //switch (GetWRefCon(window))
  3908. }
  3909.  
  3910. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3911. /*
  3912. Given a document, this will handle any clicking in the list.  The mouse
  3913. point (event.where) is expected to have been adjusted to the local
  3914. coordinates of the window.  If this routine does handle the event, then
  3915. I return true.
  3916.  
  3917. BUG NOTE: LClick will return a double-click even if no cell was selected.
  3918. So I have to test for the last click being in a real cell.  If not, then
  3919. I will not process the double click.  Also, there is another bug in the
  3920. List Manager.  It will not always deselect the currently selected cell when
  3921. the user clicks outside of the data bounds.  In other words, sometimes
  3922. my list would show 4 items when the list has room to show 8.  If the user
  3923. clicked in the bottom area of the list (below the last item) the List
  3924. Manager should deselect any items.  It doesn’t all the time, just sometimes.
  3925. The only real solution would be to write a new LClick.
  3926. */
  3927.  
  3928. #pragma segment Main
  3929. Boolean ListClick(SndDocPeek sndDoc, EventRecord *event)
  3930. {
  3931.     Cell aCell;
  3932.     Rect listRect;
  3933.     Boolean result;
  3934.  
  3935.     listRect = (**(sndDoc->list)).rView;
  3936.     listRect.right = listRect.right + kScrollbarAdjust;
  3937.     if (PtInRect(event->where, &listRect)) {
  3938.         if (LClick(event->where, event->modifiers, sndDoc->list)) {
  3939.             aCell = LLastClick(sndDoc->list);
  3940.             if ( PtInRect(aCell, &((**(sndDoc->list)).dataBounds)) )
  3941.                 PlaySelectedSnd(sndDoc, sPlayingMsg);
  3942.         }
  3943.         ActivateSndCntls(sndDoc);
  3944.         result = true;                                    //I handled the event
  3945.     } else
  3946.         result = false;
  3947.     return(result);
  3948. }
  3949.  
  3950. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3951. /*
  3952. This is called when a mouse-down event occurs in the content of my
  3953. application windows.  First thing to check for is a click in the list.
  3954. If not a list click, then find what control may have been clicked in and
  3955. handle that.
  3956.  
  3957. VERSION 1.1: Handle the record button.
  3958. */
  3959.  
  3960. #pragma segment Main
  3961. void DoSndDocClick(SndDocPeek sndDoc, EventRecord *event)
  3962. {
  3963.     ControlHandle control;
  3964.  
  3965.     SetPort((GrafPtr)sndDoc);
  3966.     GlobalToLocal(&event->where);
  3967.     if (! ListClick(sndDoc, event)) {
  3968.         if (FindControl(event->where, (WindowPtr)sndDoc, &control) != 0) {
  3969.             if (TrackControl(control, event->where, nil) != 0) {
  3970.                 switch (GetControlReference(control)) {
  3971.  
  3972.                     case rPlaySndCntl:
  3973.                         PlaySelectedSnd(sndDoc, sPlayingMsg);
  3974.                         break;
  3975.  
  3976.                     case rHyperPlayCntl:
  3977.                         PlaySelectedSnd(sndDoc, sHyperMsg);
  3978.                         break;
  3979.  
  3980.                     case rPlayScaleCntl:
  3981.                         PlaySndSong(sndDoc, rScaleSnd);
  3982.                         break;
  3983.  
  3984.                     case rMelodyCntl:
  3985.                         PlaySndSong(sndDoc, rMelodyPart1);
  3986.                         break;
  3987.  
  3988.                     case rStopCntl:
  3989.                         KillSound();
  3990.                         break;
  3991.  
  3992.                     case rRecordCntl:
  3993.                         DoRecordSound(sndDoc);
  3994.                         break;
  3995.  
  3996.                 } //switch GetControlReference(control)
  3997.             } //if TrackControl
  3998.         } //if FindControl
  3999.     } //if ! ListSelect
  4000. }
  4001.  
  4002. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4003. /*
  4004. The status window has a stop button.  This will stop any sound in
  4005. progress.  So, if the user clicks in my status window I need to check
  4006. for this.
  4007. */
  4008.  
  4009. #pragma segment Main
  4010. void DoStatClick(StatWindowPeek statWindow, EventRecord *event)
  4011. {
  4012.     ControlHandle control;
  4013.  
  4014.     SetPort((GrafPtr)statWindow);
  4015.     GlobalToLocal(&(event->where));
  4016.     if (FindControl(event->where, (WindowPtr)statWindow, &control) != 0)
  4017.         if (TrackControl(control, event->where, nil) != 0)
  4018.             KillSound();
  4019. }
  4020.  
  4021. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4022. /*
  4023. The about window has a single OK button.  If the users clicks in it, then
  4024. close the window.
  4025. */
  4026.  
  4027. #pragma segment Main
  4028. void DoAboutClick(WindowPtr window, EventRecord *event)
  4029. {
  4030.     ControlHandle control;
  4031.     Boolean ignore;
  4032.  
  4033.     SetPort(window);
  4034.     GlobalToLocal(&event->where);
  4035.     if (FindControl(event->where, (WindowPtr)window, &control) != 0) {
  4036.         if (TrackControl(control, event->where, nil) != 0)
  4037.             ignore = DoCloseWindow(window);
  4038.     }
  4039. }
  4040.  
  4041. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4042. /*
  4043. This is called when an update event is received for any of my windows.  It
  4044. calls the appropriate window’s update routine to draw its contents.  As an
  4045. efficiency measure that does not have to be followed, it calls the drawing
  4046. routine only if the visRgn is non-empty.  This will handle situations
  4047. where calculations for drawing or drawing itself is very time-consuming.
  4048. Why does QD give you an update with an empty updateRgn?
  4049. */
  4050.  
  4051. #pragma segment Main
  4052. void DoUpdate(WindowPtr window)
  4053. {
  4054.     BeginUpdate(window);                            //setup the visRgn, clears updateRgn
  4055.     if (! EmptyRgn(window->visRgn)) {                 //if updating to be done
  4056.         SetPort(window);                            //set to the current port
  4057.         switch (GetWRefCon(window)) {                //call the window’s drawing routine
  4058.  
  4059.             case rSoundWindow:
  4060.                 DrawSndWindow(window);
  4061.                 break;
  4062.  
  4063.             case rStatusWindow:
  4064.                 DrawStatusWindow();
  4065.                 break;
  4066.  
  4067.             case rAboutWindow:
  4068.                 DrawAboutWindow(window);
  4069.                 break;
  4070.         }
  4071.     }
  4072.     EndUpdate(window);                                //restores the visRgn
  4073. }
  4074.  
  4075. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4076. /*
  4077. This is called when a window is to be activated or deactivated.  For the
  4078. document window I activate all the controls and the list.  For the status
  4079. window I activate the one and only control.  This is also called for
  4080. suspend and resume events while running MultiFinder.
  4081. */
  4082.  
  4083. #pragma segment Main
  4084. void DoActivate(WindowPtr window, Boolean becomingActive)
  4085. {
  4086.     if (window != nil) {
  4087.         switch (GetWRefCon(window)) {
  4088.  
  4089.             case rSoundWindow:
  4090.                 ActivateSndCntls((SndDocPeek)window);
  4091.                 LActivate(becomingActive, ((SndDocPeek)window)->list);
  4092.                 break;
  4093.  
  4094.             case rStatusWindow:
  4095.                 if (becomingActive)                            //it only has one control
  4096.                     HiliteControl(((WindowPeek)window)->controlList, kControlNoPart);
  4097.                 else
  4098.                     HiliteControl(((WindowPeek)window)->controlList, kControlInactivePart);
  4099.                 DoButtonOutline(((WindowPeek)window)->controlList);
  4100.                 break;
  4101.  
  4102.             case rAboutWindow:
  4103.                 if (becomingActive)                            //it only has one control
  4104.                     HiliteControl(((WindowPeek)window)->controlList, kControlNoPart);
  4105.                 else
  4106.                     HiliteControl(((WindowPeek)window)->controlList, kControlInactivePart);
  4107.                 DoButtonOutline(((WindowPeek)window)->controlList);
  4108.                 break;
  4109.         }
  4110.     }
  4111. }
  4112.  
  4113. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4114. /*
  4115. The required AppleEvent sent to tell an application to quit. Nothing much to do.
  4116. Just call our terminate routine to clean up and then exit through the event loop.
  4117. Note that you cannot exit from here, the system will crash. You must return to
  4118. the AppleEvent Manager. Do not call ExitToShell at this point!
  4119. */
  4120.  
  4121. #pragma segment Main
  4122. pascal OSErr QuitApplicationEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
  4123. {
  4124. #pragma unused (theAppleEvent, reply, handlerRefcon)
  4125.  
  4126.     Terminate();
  4127.     return(noErr);
  4128. }
  4129.  
  4130. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4131. /*
  4132. One of the required AppleEvents. This is a request to open a document. Find
  4133. the document being requested, and open it.
  4134. */
  4135.  
  4136. #pragma segment Main
  4137. pascal OSErr OpenDocumentsEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
  4138. {
  4139. #pragma unused (reply, handlerRefcon)
  4140.  
  4141.     FSSpec                file;
  4142.     AEDescList            docList;
  4143.     long                i;
  4144.     long                itemsInList;
  4145.     Size                actualSize;
  4146.     AEKeyword            keyword;
  4147.     DescType            returnedType;
  4148.     OSErr                theErr;
  4149.  
  4150.     // get the direct parameter--a descriptor list--and put it into docList
  4151.     theErr = AEGetParamDesc(theAppleEvent, keyDirectObject, typeAEList, &docList);
  4152.     if (theErr == noErr)
  4153.     {
  4154.         if (docList.descriptorType != typeAEList)
  4155.         {
  4156.             AEDisposeDesc (&docList);
  4157.             theErr = paramErr;
  4158.         }
  4159.         else
  4160.         {
  4161.             // count the number of descriptor records in the list
  4162.             theErr = AECountItems(&docList, &itemsInList);
  4163.             if (theErr == noErr)
  4164.             {
  4165.                 //get each descriptor record from the list, coerce the returned data
  4166.                 //to an FSSpec and open the associated file
  4167.  
  4168.                 for (i = 1; i <= itemsInList; i++)
  4169.                 {
  4170.                     theErr = AEGetNthPtr(&docList, i, typeFSS, &keyword, &returnedType,
  4171.                                             &file, sizeof(file), &actualSize);
  4172.                     if (theErr == noErr)
  4173.                         OpenSoundDoc(&file);
  4174.                 }
  4175.             }
  4176.             AEDisposeDesc (&docList);
  4177.         }
  4178.     }
  4179.     return (theErr);
  4180. }
  4181.  
  4182. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4183. /*
  4184. It's a required AppleEvent and we don't use it.
  4185. */
  4186.  
  4187. #pragma segment Main
  4188. pascal OSErr PrintDocumentsEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
  4189. {
  4190. #pragma unused (theAppleEvent, reply, handlerRefcon)
  4191.  
  4192.     return (errAEEventNotHandled);
  4193. }
  4194.  
  4195. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4196. /*
  4197. It's a required AppleEvent and we don't use it.
  4198. */
  4199.  
  4200. #pragma segment Main
  4201. pascal OSErr OpenApplicationEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
  4202. {
  4203. #pragma unused (theAppleEvent, reply, handlerRefcon)
  4204.  
  4205.     return (noErr);
  4206. }
  4207.  
  4208. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4209. /*
  4210. As Spike Lee says, “Do the right thing.” Determine what kind of event it
  4211. is, and call the appropriate routines.  Key down events are first tested
  4212. as being command key events for menus or command-. for cancel.  If it’s
  4213. the command-. the user is asking to cancel the sound.  In this case, if
  4214. the front window is the status window then the button should look as if it
  4215. has been clicked.  This is proper human interface.  Any non-menu command
  4216. keys are passed to DoKeyDown.  I have a global flag, gInModalState, which
  4217. is used to handle the front window as a modal dialog.  This means I ignore
  4218. clicks outside of the modal window and menu command keys.  I could have a
  4219. different global flag that would mean it’s a modal window but uses menu
  4220. commands, such as gInModalMenuState.  An important note is that I do pass
  4221. any other non-menu command keys to DoKeys, so the modal window could have
  4222. access to key events.  One last thing to note happens during a suspend
  4223. event.   Applications using sound should dispose of their sound channels
  4224. at suspend time.  No other application can use sound while another one has
  4225. channels allocated.  To stop my sound, I call KillSound which hides the
  4226. status window.  MultiFinder does properly deactivate the front window at
  4227. suspend time and applications normally do not have to worry about
  4228. HiliteWindow.  I do because the front window could have been the status
  4229. window and I’ve removed it after getting a suspend event.  This causes the
  4230. next window, a document window, to become highlighted as the active
  4231. window.  To avoid my next window from being highlighted while in the
  4232. background, I have to call HiliteWindow *after* KillSound.  This is
  4233. strange and only applications changing the front window at suspend event
  4234. time have to be concerned about this.
  4235.  
  4236. VERSION 1.1: Added a constant, kSFTopLeft, to specify the dialog position.
  4237. I do not call KillSound during a MultiFinder switch unless we're running
  4238. the older Sound Manager.  The new one allows for multiple sound
  4239. channels or will return the proper error otherwise.
  4240. */
  4241.  
  4242. #pragma segment Main
  4243. void DoEvent(EventRecord *event)
  4244. {
  4245.     WindowPtr window;
  4246.     Point where;
  4247.     short part;
  4248.     short err;
  4249.     Boolean ignore;
  4250.     char key;
  4251.  
  4252.     switch (event->what) {
  4253.  
  4254.         case mouseDown:
  4255.             part = FindWindow(event->where, &window);
  4256.             if (    (IsModalWindow(FrontWindow()) && (window != FrontWindow()))
  4257.                  || (IsModalWindow(FrontWindow()) && (part == inMenuBar)))
  4258.             {
  4259.                 SysBeep(30);                            //click outside of modal window
  4260.                 return;                                    //break out of routine
  4261.             }
  4262.             switch (part) {
  4263.                 case inMenuBar:                                //process the menu command
  4264.                     AdjustMenus();
  4265.                     DoMenuCommand(MenuSelect(event->where));
  4266.                     break;
  4267.  
  4268.                 case inSysWindow:                            //let system handle the mouseDown
  4269.                     SystemClick(event, window);
  4270.                     break;
  4271.  
  4272.                 case inContent:
  4273.                     if ((window != FrontWindow()))
  4274.                         SelectWindow(window);
  4275.                     else {
  4276.                         switch (GetWRefCon(window)) {
  4277.  
  4278.                             case rSoundWindow:
  4279.                                 DoSndDocClick((SndDocPeek)window, event);
  4280.                                 break;
  4281.  
  4282.                             case rStatusWindow:
  4283.                                 DoStatClick((StatWindowPeek)window, event);
  4284.                                 break;
  4285.  
  4286.                             case rAboutWindow:
  4287.                                 DoAboutClick(window, event);
  4288.                                 break;
  4289.  
  4290.                             } //switch (GetWRefCon(window))
  4291.                         }
  4292.                     break; //inContent
  4293.  
  4294.                 case inDrag:                        //pass screenBits.bounds to get all gDevices
  4295.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  4296.                     break;
  4297.  
  4298.                 case inGoAway:
  4299.                     if (TrackGoAway(window, event->where))
  4300.                         ignore = DoCloseWindow(window);
  4301.                     break;
  4302.  
  4303.             } //switch (part)
  4304.             break; //mouseDown
  4305.  
  4306.         case keyDown:
  4307.         case autoKey:
  4308.             window = FrontWindow();
  4309.             key = event->message & charCodeMask;
  4310.             if ((event->modifiers & cmdKey) != 0)            //Command key down?
  4311.             {
  4312.                 if (key == kPeriod)
  4313.                 {
  4314.                     if (window == (WindowPtr)gStatusWindow)
  4315.                         SelectButton(((WindowPeek)gStatusWindow)->controlList);
  4316.                     KillSound();
  4317.                 } else
  4318.                     if ((event->what == keyDown) && (! IsModalWindow(window)))
  4319.                     {
  4320.                         AdjustMenus();                        //adjust items properly
  4321.                         DoMenuCommand(MenuKey(key));
  4322.                     }
  4323.             } else                                            //non-Command keys
  4324.                 if (window != nil)                            //if there’s a window
  4325.                     DoKeyDown(key, window);
  4326.             break;
  4327.  
  4328.         case activateEvt:                        //true for activate, false for deactivate
  4329.             DoActivate((WindowPtr)event->message, event->modifiers & activeFlag);
  4330.             break;
  4331.  
  4332.         case updateEvt:                            //call DoUpdate with the window to update
  4333.             DoUpdate((WindowPtr)event->message);
  4334.             break;
  4335.  
  4336.         case diskEvt:                                //Call DIBadMount in response to a diskEvt
  4337.             if (HighWord(event->message) != noErr) {
  4338.                 where.v = kRecordTop;
  4339.                 where.h = kRecordLeft;
  4340.                 err = DIBadMount(where, event->message);
  4341.             }
  4342.             break;
  4343.  
  4344.         case osEvt:
  4345.             switch (event->message >> 24) {                    //get high byte of message
  4346.  
  4347.                 case suspendResumeMessage:
  4348.                     if ((event->message & suspendResumeMessage) != 0)
  4349.                         gInBackground = false;                //it was a resume event
  4350.                     else {
  4351.                         gInBackground = true;                //it was a suspend event
  4352.                         if (GetSoundMgrVersion() == 1)
  4353.                             KillSound();                    //stop any sound
  4354.                         window = FrontWindow();                //get front window
  4355.                         if (window != nil)                     //don’t use a nil window
  4356.                             HiliteWindow(window, false);    //then properly activate it
  4357.                     }
  4358.                     DoActivate(FrontWindow(), ! gInBackground);
  4359.                     break; //suspendResumeMessage
  4360.             }
  4361.             break; //osEvt
  4362.  
  4363.         case kHighLevelEvent:
  4364.             AEProcessAppleEvent(event);
  4365.             break;
  4366.  
  4367.     } //switch (event->what)
  4368. }
  4369.  
  4370. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4371. /*
  4372. Change the cursor’s shape, depending on its current position.  This also
  4373. calculates the region where the current cursor resides (for
  4374. WaitNextEvent).  This is based on its current position in global
  4375. coordinates.  If the mouse is ever outside of that region, an event is
  4376. generated causing this routine to be called again by the event loop.  This
  4377. allows me to change the region to where the mouse is currently located.
  4378. If there is more to the event than just “the mouse moved,” this gets
  4379. called before the event is processed to make sure the cursor is the right
  4380. one.  In any (ahem) event, this is called again before I fall back into
  4381. WaitNextEvent.  Extreme short values are used to create a wide open
  4382. region.  -SHRT_MAX - 1 is the largest negative short (-32768) and SHRT_MAX
  4383. is the largest positive short (32767).
  4384.  
  4385. BUG NOTE: The largest positive value for a region’s size is SHRT_MAX - 1
  4386. due to a very old bug that still remains to this day.
  4387. */
  4388.  
  4389. #pragma segment Main
  4390. void AdjustCursor(RgnHandle region)
  4391. {
  4392.     WindowPtr window;
  4393.     RgnHandle arrowRgn;
  4394.     RgnHandle sndCursorRgn;
  4395.     Rect sndCursorRect;
  4396.  
  4397.     window = FrontWindow();            //I only adjust the cursor when I am in front
  4398.     if ((! gInBackground) && (! IsDAWindow(window))) {
  4399.  
  4400.         arrowRgn = NewRgn();        //calculate regions for different cursor shapes
  4401.         sndCursorRgn = NewRgn();    //start with a big, big rectangular region
  4402.         SetRectRgn(arrowRgn, -SHRT_MAX - 1, -SHRT_MAX - 1, SHRT_MAX - 1, SHRT_MAX - 1);
  4403.  
  4404.         if (IsDocWindow(window)) {                //calculate region for document cursor
  4405.             sndCursorRect = window->portRect;
  4406.             SetPort(window);
  4407.  
  4408.             //make a global version of the viewRect
  4409.             LocalToGlobal(&TopLeft(sndCursorRect));
  4410.             LocalToGlobal(&BottomRight(sndCursorRect));
  4411.             RectRgn(sndCursorRgn, &sndCursorRect);
  4412.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  4413.             SectRgn(sndCursorRgn, window->visRgn, sndCursorRgn);
  4414.             SetOrigin(0, 0);
  4415.         }
  4416.  
  4417.         DiffRgn(arrowRgn, sndCursorRgn, arrowRgn);    //subtract other region
  4418.         if (PtInRgn(GetGlobalMouse(), sndCursorRgn)) {
  4419.             SetCursor(*(GetCursor(rSndCursor)));     //change cursor and region
  4420.             CopyRgn(sndCursorRgn, region);
  4421.         } else {
  4422.             SetCursor(&qd.arrow);
  4423.             CopyRgn(arrowRgn, region);
  4424.         }
  4425.         DisposeRgn(arrowRgn);                        //get rid of our local regions
  4426.         DisposeRgn(sndCursorRgn);
  4427.     }
  4428. }
  4429.  
  4430. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4431. /*
  4432. Get events forever, and handle them by calling DoEvent.  Since this
  4433. application requires System 6.0x or later I know that _WaitNextEvent is
  4434. always there, even without MultiFinder.  MultiFinder’s sleep is used to
  4435. determine how often I want to receive events, regardless if an event has
  4436. actually occurred.  In this application, I don’t perform any background
  4437. processing so I’m being super friendly by using LONG_MAX as a sleep
  4438. value.  This also helps keep Virtual Memory from paging me in just to run
  4439. my event loop and find out that nothing happened.  The application will
  4440. only be called upon for events that must be handled.  Also call
  4441. AdjustCursor each time through the loop.  AdjustCursor will return the
  4442. current region containing the mouse and is passed to WaitNextEvent.  If
  4443. the mouse travels out of the region, another event is generated.  I have
  4444. to call AdjustCursor just before doing the event to make sure the right
  4445. cursor is shown.  Another thing, if I have a sound playing asynchronously
  4446. then I want to dispose of my channel as soon as possible.  I set up a flag
  4447. in the SoundUnit that will keep track of when it has a channel allocated.
  4448. I can call the HasChannelOpen() function to find out if this is true.  It
  4449. pretty much like keeping track of when you’re in the background.  If a
  4450. channel is open, then the MultiFinder sleep time is adjusted to a
  4451. reasonable time that will allow me to catch when the sound has completed
  4452. so that I may dispose of my channels and status window.  That’s when I
  4453. return kPollingSleepTime.
  4454.  
  4455. VERSION 1.1: No longer putting the SANELib into a seperate segment, which then
  4456. needed to be unloaded.  Instead, I merge it into the Main segment.  Refer
  4457. to the Make file for further information.
  4458.  
  4459. VERSION 1.2: No longer using the SANELib at all. All of the SANE calls
  4460. are inline, and do not need a library to be linked in.
  4461. */
  4462.  
  4463. #pragma segment Main
  4464. void EventLoop(void)
  4465. {
  4466.     RgnHandle cursorRgn;
  4467.     EventRecord event;
  4468.     long sleep;
  4469.  
  4470.     cursorRgn = NewRgn();                    //1st time pass WNE an empty region
  4471.     while (!gTerminate) {
  4472.         if (HasChannelOpen())                //if we’re playing a sound
  4473.             sleep = kPollingSleepTime;        //use the polling sleep value
  4474.         else {
  4475.             sleep = LONG_MAX;                //default value for sleep
  4476.             UnloadSeg(_SoundUnit);            //unload the Sound Unit
  4477.         }
  4478.         UnloadSeg(OpenSoundDoc);            //unload the open code
  4479.         if (HasSoundCompleted())
  4480.             KillSound();
  4481.         if (LowOnReserve())
  4482.             RecoverReserve();
  4483.         AdjustCursor(cursorRgn);            //get the right cursor
  4484.         if (WaitNextEvent(everyEvent, &event, sleep, cursorRgn)) {
  4485.             AdjustCursor(cursorRgn);        //get the right cursor
  4486.             DoEvent(&event);
  4487.         }
  4488.     };                                        //loop forever; I quit through Terminate
  4489. }
  4490.  
  4491. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4492. /*
  4493. Set up the whole world.  Initialize global variables, Toolbox managers,
  4494. and menus.  If a failure occurs here, I will consider that the application
  4495. is in such bad shape that I should just exit.  Your error handling may
  4496. differ, but the checks should still be made.  I ask for a set of master
  4497. pointer blocks and all permanent storage at this point to cut down on
  4498. memory fragmentation.  I may be opening large numbers of resources and
  4499. documents so I allocate some extra master pointer blocks at the start.
  4500.  
  4501. VERSION 1.1:  Now supports opening of documents from the Finder.
  4502. */
  4503.  
  4504. #pragma segment Initialize
  4505. void Initialize(void)
  4506. {
  4507. #define kBroughtToFront    3
  4508.  
  4509.     EventRecord event;
  4510.     Handle menuBar;
  4511.     long response;
  4512.     short count;
  4513.     OSErr ignoreErr;
  4514.     Boolean ignoreResult;
  4515.  
  4516.     gTerminate = false;
  4517.     gInBackground = false;                        //we’ll be in the foreground soon
  4518.     gAppResRef = CurResFile();                    //save the resRef to myself
  4519.     for (count = 1; count <= kNumberOfMasters; count++)    //allocate master pointer blocks
  4520.         MoreMasters();
  4521.     InitGraf(&qd.thePort);                        //init managers, yawn...
  4522.     InitFonts();
  4523.     InitWindows();
  4524.     InitMenus();
  4525.     TEInit();
  4526.     InitDialogs(nil);
  4527.     InitCursor();
  4528.  
  4529. /*
  4530. ErrorSound is used to prevent the Dialog Manager from calling _SysBeep.
  4531. If I get a memory or resource Manager error it wouldn’t be the best
  4532. of plans to call _SysBeep which will want to allocate memory and load
  4533. a few resources.  Which could be bad if I just gave an Alert signalling
  4534. an out of memory condition. You only have to install this for Sound Manager
  4535. version  1 which is pretty buggy.
  4536.  
  4537. VERSION 1.2: Since we're using Sound Manager 2 or later, we don't have to
  4538. disable the multiple sampled sound channels demo and we don't need DoErrorSound.
  4539.  
  4540.     if (GetSoundMgrVersion() == 1)
  4541.     {
  4542.         ErrorSound(GetRoutineAddress(DoErrorSound));
  4543.         DisableItem(GetMenu(mDemos), iSampleSATB);
  4544.         DisableItem(GetMenu(mDemos), iSampleMelody);
  4545.     }
  4546. */
  4547.  
  4548. /*
  4549. This code is necessary to pull the application into the foreground.  I use
  4550. EventAvail because I don’t want to remove any events the user may have
  4551. done, such as typing ahead.  Until the application has made a few calls (3
  4552. seems to be the magic number) to the Event Manager, MultiFinder keeps me
  4553. in the background.   Splashscreens and Alerts will remain in a background
  4554. layer until we get a few events.  This is documented in Tech Note #180.
  4555. */
  4556.  
  4557.     for (count = 1; count <= kBroughtToFront; count++)
  4558.         ignoreResult = EventAvail(everyEvent, &event);
  4559.  
  4560. /*
  4561. Ignore the error returned from SysEnvirons; even if an error occurred,
  4562. the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  4563. call to SysEnvirons by calling it after initializing AppleTalk.
  4564.  
  4565. VERSION 1.2: Using Gestalt and checking for System 7. Make sure you know if
  4566. the Gestalt trap is available before calling it. This code is compiled with the
  4567. SystemSevenOrLater flag on, when means you do not get the safe glue for Gestalt.
  4568. */
  4569.     if (! TrapExists(_Gestalt))
  4570.         EmergencyExit(sWrongVersion);
  4571.  
  4572.     if (Gestalt(gestaltSystemVersion, &response) != noErr)
  4573.         EmergencyExit(sStandardErr);
  4574.  
  4575.     if (response < 0x0700)
  4576.         EmergencyExit(sWrongVersion);
  4577.  
  4578. /*
  4579. Call the SoundUnit to initialize itslef.  If the SoundUnit encounters an error,
  4580. then it cannot be used and this means I’m leaving too.
  4581. */
  4582.  
  4583.     if (InitSoundUnit() != noErr)                //allocates 4 * 1064 bytes
  4584.         EmergencyExit(sInitSoundErr);
  4585.  
  4586. /*
  4587. Before I go any further, I want my reserve memory.  This is an emergency
  4588. reserve (sorta like my old VW had) when memory runs low.  If I cannot
  4589. obtain this reserve, then I’ll bail.  It’s also important to obtain my
  4590. reserve before testing if I have the desired amount of memory to run
  4591. this application.  Also, FailLowMemory will consider the memory reserve.
  4592. */
  4593.  
  4594.     if (! AllocateReserve())
  4595.         EmergencyExit(sLowMemory);
  4596.     SetGrowZone(GetRoutineAddress(MyGrowZone));
  4597.  
  4598.     menuBar = GetNewMBar(rMenuBar);                    //read menus into menu bar
  4599.     if (menuBar == nil)
  4600.         EmergencyExit(sNoMenus);                    //wow, how’d that happen?
  4601.     SetMenuBar(menuBar);                            //install menus
  4602.     DisposeHandle(menuBar);
  4603.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    //add DA names to Apple menu
  4604.     DrawMenuBar();
  4605.  
  4606.     InitStatusWindow();                                //get the status window ready
  4607.     InitCursorCtl(nil);                                //MPW’s handy cursor routines
  4608.  
  4609. /*
  4610. Last, I want to make sure that enough memory is free for my application to
  4611. run.  It is possible that user may have adjusted the SIZE resource to too
  4612. small a setting or for some other reason the application started up in a
  4613. very small memory partition.  It’s also possible for a situation to arise
  4614. where the heap may have been of the requested size taken from the SIZE
  4615. resource, but a large scrap was loaded which left too little memory.  I
  4616. want to make sure that my free memory is not being modified by the scrap’s
  4617. presence.  So, I unload it to disk but if the application will run once
  4618. the scrap is unloaded, then you’ll probably not get it back into memory.
  4619. Thus losing the clipboard contents.  I preform this check after
  4620. initializing all the Toolbox and the basic features of this application,
  4621. such as showing the about box.
  4622. */
  4623.     if (FailLowMemory(kMinSpace)) {
  4624.         if (UnloadScrap() != noErr)
  4625.             EmergencyExit(sLowMemory);
  4626.         else {
  4627.             if (FailLowMemory(kMinSpace))
  4628.                 EmergencyExit(sLowMemory);
  4629.         }
  4630.     }
  4631.  
  4632. /*
  4633. Install the four core AppleEvent handlers.
  4634. */
  4635.     ignoreErr = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
  4636.                 GetRoutineAddress(QuitApplicationEvent), 0, false);
  4637.  
  4638.     ignoreErr = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
  4639.                 GetRoutineAddress(OpenDocumentsEvent), 0, false);
  4640.  
  4641.     ignoreErr = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
  4642.                 GetRoutineAddress(PrintDocumentsEvent), 0, false);
  4643.  
  4644.     ignoreErr = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
  4645.                  GetRoutineAddress(OpenApplicationEvent), 0, false);
  4646. }
  4647.  
  4648. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4649. /*
  4650. This routine is contained in the MPW runtime library.  It will be placed
  4651. into the code segment used to initialize the A5 globals.  This external
  4652. reference to it is done so that we can unload that segment, named %A5Init.
  4653. */
  4654.  
  4655. #ifdef applec
  4656. extern void _DataInit(void);
  4657. #endif
  4658.  
  4659. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4660. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN PROGRAM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4661. /*
  4662. If you have stack requirements that differ from the default, then you
  4663. could use SetApplLimit to increase StackSpace at this point, before
  4664. calling MaxApplZone.
  4665. */
  4666.  
  4667. #pragma segment Main
  4668. void main(void)
  4669. {
  4670. #ifdef applec
  4671.     UnloadSeg(_DataInit);            //note that _DataInit must not be in Main!
  4672. #endif
  4673.     MaxApplZone();                    //expand the heap so code segments load at the top
  4674.     Initialize();                    //initialize the program
  4675.     UnloadSeg(Initialize);            //note that Initialize must not be in Main!
  4676.     EventLoop();                    //call the main event loop
  4677.     ExitToShell();                    //we're out of here!
  4678. }
  4679. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN PROGRAM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4680. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4681.